简体   繁体   中英

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

只需检查是否mymap.find('b') != mymap.end()

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM