C++ Check if a Key Exists in the Unordered Map
To check if a key exists in an unordered map in C++, you can use the find()
function. The find()
function returns an iterator to the element with the specified key if it is found in the map, and end()
if it is not found.
Here's an example:
#include <iostream> #include <unordered_map> int main() { std::unordered_map<std::string, int> myMap = {{"apple", 1}, {"banana", 2}, {"orange", 3}}; // Check if "banana" exists in the map auto it = myMap.find("banana"); if (it != myMap.end()) { std::cout << "The value of \"banana\" is " << it->second << std::endl; } else { std::cout << "The key \"banana\" is not found in the map." << std::endl; } // Check if "grape" exists in the map it = myMap.find("grape"); if (it != myMap.end()) { std::cout << "The value of \"grape\" is " << it->second << std::endl; } else { std::cout << "The key \"grape\" is not found in the map." << std::endl; } return 0; }
Output:
The value of "banana" is 2 The key "grape" is not found in the map.
In this example, we create an unordered map called myMap
with three key-value pairs. We use the find()
function to check if the keys "banana" and "grape" exist in the map. The find()
function returns an iterator to the element with the specified key if it is found in the map, and end()
if it is not found. We use an if
statement to check if the iterator is equal to end()
, which indicates that the key is not found in the map. If the iterator is not equal to end()
, we print the value of the key-value pair.