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

0

I'm doing a TAD of graphs and I use a map structure to map the ID of a vertex to its index in the adjacency array and to do that I need to first check if given the vertex id it's already added to the graph, so how can I check if there is a mapped value for a particular key? the code is more or less something like

bool Graph::add_edge(vertex o, vertex d){
    ///if(index[o] existe)
    /// if(index[d] existe)
        ///add aresta
}
    
asked by anonymous 02.07.2017 / 23:59

1 answer

2

Just use the method find of std::map . This will return an iterator, if the iterator is not equal to end() of your map, then it means that 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;
}
    
03.07.2017 / 02:11