How to check if the value of a key exists on a map in c++

Asked

Viewed 574 times

0

I am doing a graph TAD and I use a map structure to map the ID of a vertex to its index in the adjacency matrix and to do this I need to first check if given the vertex id it is already added to the graph, then how can I verify if there is a mapped value for a given key? the code is something like this

bool Graph::add_edge(vertex o, vertex d){
    ///if(index[o] existe)
    /// if(index[d] existe)
        ///add aresta
}

1 answer

2


Just use the method find of std::map. This will return an iterator if the iterator is not equal to the iterator end() from your map, so that means the key value exists. Example:

#include <iostream>
#include <string>
#include <map>
using namespace std;


void existe(const string& nome, const map<string, int>& pessoas)
{
    auto res = pessoas.find(nome);
    if (res != pessoas.end())
        cout << "-- " << nome << " esta no std::map!\n";
    else
        cout << "-- " << nome << " nao esta no std::map!\n";
}


int main()
{
    map<string, int> pessoas;

    pessoas["john"] = 22;
    pessoas["mary"] = 30;
    pessoas["ethan"] = 40;
    pessoas["larry"] = 12;

    existe("john", pessoas);
    existe("peter", pessoas);
    existe("larry", pessoas);
    existe("alice", pessoas);

    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.