Akavall
Akavall

Reputation: 86356

How can I check if an element is in map keys in C++?

I am wonder if there is a way I can check if an element is included in map keys. For example:

#include<iostream>
#include<map>

using namespace std;

int main()
{

map<char, int> mymap;

mymap['a'] = 1;
mymap['b'] = 2;
mymap['z'] = 26;

// I want to check if 'b' is one of the keys in map mymap.

    return 0;
}

Elements 'a', 'b' and 'z' are the keys of map mymap. I want a command that will return true if element is in keys of a map and false if the elements is not in keys of a map. I looked around, but could find a quick build-in method that does this. Did I miss anything? Is there a such a method?

Here is a long way that gets me my desired outcome:

#include<iostream>
#include<map>

using namespace std;

bool check_key(map<char, int> mymap, char key_val);

int main()
{

map<char, int> mymap;

mymap['a'] = 1;
mymap['b'] = 2;
mymap['z'] = 26;

char key_val = 'h';

cout<<mymap.find('z')->first<<endl;

cout<<"checking "<< check_key(mymap, 'h')<<endl;
cout<<"checking "<< check_key(mymap, 'b')<<endl;

    return 0;
}

bool check_key(map<char, int> mymap, char key_val){

    for (map<char, int>::const_iterator it = mymap.begin(); it != mymap.end(); ++it ){
        if (key_val == it->first){
            return true;
        }

    }
    return false;

}

Thank You in Advance

Upvotes: 0

Views: 253

Answers (2)

pmdj
pmdj

Reputation: 23448

You can check if a key is present by comparing the result of find() to the iterator returned by end():

std::map<char, int> my_map;
// add items
std::map<char, int>::iterator found = my_map.find('b');
if (found == my_map.end())
{
  // 'b' is not in the map
}

Upvotes: 7

Kerrek SB
Kerrek SB

Reputation: 477640

Simply check whether mymap.find('b') != mymap.end().

Upvotes: 12

Related Questions