This article will examine several approaches for determining whether a certain key already exists in a C++ std::map.
How to Find a Given Key Exists in a C++ std::map
There are two methods to check if a given key exists in a C++ std::map.
Method 1: std::map::find
find() is a useful function in C++ that can be used to find a given key exist in a C++ std:: map. The function accepts a single input of the key value and searches for it. If an element with a key comparable to k is discovered, the map::find(k) function returns an iterator to it; otherwise, it returns an iterator to map::end. The user input given to the find() function is used to obtain the key value after initializing the map of any std::pair type.
#include <string>
#include <map>
int main()
{
std::map<std::string, int> map = {
{"english", 1}, {"maths", 2}, {"science", 3}
};
std::string key = "history";
if (map.find(key) != map.end()) {
std::cout << "Key found!" << std::endl;
} else {
std::cout << "Key not found!" << std::endl;
}
return 0;
}
In the above code, we are initializing a map with keys and values. Then we define a key named “history”, and use the find() method and if statement to search if that key exists in the map or not.
Output
Method 2: std::map::count
count() is another built-in function to find a given key exists in a C++ in the std::map. This function returns the number of entries that match the specified key value. If the specified key is found in the map, the count() method returns 1, else it returns 0. This is because a map in C++ only keeps track of unique keys. In order to print the affirming text when the specified key exists in a map object, we may use the count() function call as an if condition.
#include <string>
#include <map>
int main()
{
std::map<std::string, int> map = {
{"english", 1}, {"maths", 2}, {"science", 3}
};
std::string key = "maths";
if (map.count(key) != 0) {
std::cout << "Key found!" << std::endl;
} else {
std::cout << "Key not found!" << std::endl;
}
return 0;
}
In the above code, we are initializing a map with keys and values. Then we define a key named “maths”, and use the count() method and if statement to search if that key exists in the map or not.
Output
Conclusion
The std::map container is a data structure made up of key-value pairs that are kept ordered and each element has a distinct key. There are two methods mentioned in the article above, find() function and count() function, to find if a given key exists in a C++ std::map. These methods can be used to locate a certain key in your C++ code.