C++ map :: find() function – Example to find an element by key into a map. Also, check if key exists into a map in C++ program.
std::find function accept a key as an argument. So, pass the key to the find() function for which you want to get or check value in the map.
If the key exist in the map, then it will return an iterator and if key is not present in the map, then the find function will return map.end().
Note – By using the iterator, you can get the value. But, first check if iterator is not equal to map.end() or else if the key is not present , then the program will crash.
std::map::find() function declaration
iterator find (const key_type& key);
const_iterator find (const key_type& k) const;
C++ map::find example
In this example, we have some key value pair in the map. a character as key and a string as value e.g.
‘a’,”Apple”
‘-‘,”Minus”
‘+’,”Plus”
‘$’,”Doller”
The program will find string value by key using std::map::find function. The program will check if key exists or not. If key is not present in the map, then conditional validation is there and program will say “key not present in the map”.
#include <map> // Include map
#include <iostream>
using namespace std;
int main() {
/* Create a hash map - char as key and string as value*/
std::map<char, std::string> m;
/* Insert some elements ( key value pair) in the hash map */
m.insert(std::pair<char, string>('a', "Apple"));
m.insert(std::pair<char, string>('-', "Minus"));
m.insert(std::pair<char, string>('+', "Plus"));
m.insert(std::pair<char, string>('$', "Dollar"));
// Finding value using a key in the hash map
//Declare a map Iterator
std::map<char, string>::iterator itr;
//find() function returns iterator if key exists or else
// returns m.end()
itr = m.find('$');
// check if iterator is not equal to m.end()
if (itr != m.end()) {
cout << "Key => " << itr->first << ", Value => " << itr->second.c_str() << endl;
}
else
{
cout << "Key not present in the map" << endl;
}
return 0;
}
Output:
If you find the key which is present e.g. $, then output well be as below.
Key => $, Value => Dollar
If you find the key which is not present e.g. x, then output well be as below.
Key not present in the map