Determine if a key exists in a map in C++
This post will discuss how to determine if a key exists in a map in C++.
1. Using std::map::find
The standard way to use the std::map::find function that searches a map for a key and returns an iterator to it, or the std::map::end if the key is not present in the map. The following code example shows invocation for this function:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <string> #include <map> int main() { std::map<std::string, int> map = { {"one", 1}, {"two", 2}, {"three", 3} }; std::string key = "two"; if (map.find(key) != map.end()) { std::cout << "Key found" << std::endl; } else { std::cout << "Key not found" << std::endl; } return 0; } |
Output:
Key found
2. Using std::map::count
Another option is to use std::map::count to get the total number of elements in the map with a particular key. If a key is present in the map, the count would be exactly 1 since all keys in the map container are unique. If the key is not found, the count function returns zero.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <string> #include <map> int main() { std::map<std::string, int> map = { {"one", 1}, {"two", 2}, {"three", 3} }; std::string key = "two"; if (map.count(key) != 0) { std::cout << "Key found" << std::endl; } else { std::cout << "Key not found" << std::endl; } return 0; } |
Output:
Key found
3. Using std::map::contains
Another option to check whether a particular key exists in the map is using the std::map::contains member function. This function is available since C++20. It returns true if the map contains an element with a specific key, false otherwise.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <string> #include <map> int main() { std::map<std::string, int> map = { {"one", 1}, {"two", 2}, {"three", 3} }; std::string key = "two"; if (map.contains(key)) { std::cout << "Key found" << std::endl; } else { std::cout << "Key not found" << std::endl; } return 0; } |
Output:
Key found
That’s all about determining if a key exists in a map in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)