c++ unordered_map check if key exists

To check if a key exists in a C++ unordered_map, you can follow these steps:

  1. Declare an unordered_map variable and initialize it if necessary.
  2. Use the find() function of the unordered_map to search for the specified key.
  3. The find() function returns an iterator pointing to the element if the key is found, or an iterator pointing to the end of the unordered_map if the key is not found.
  4. Check if the iterator returned by find() is equal to the end iterator, which indicates that the key was not found.

Here is an example that demonstrates these steps:

#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_map<std::string, int> myMap = {{"apple", 1}, {"banana", 2}, {"orange", 3}};

    std::string key = "banana";
    auto it = myMap.find(key);

    if (it != myMap.end()) {
        std::cout << "Key '" << key << "' exists in the unordered_map." << std::endl;
    } else {
        std::cout << "Key '" << key << "' does not exist in the unordered_map." << std::endl;
    }

    return 0;
}

In this example, we have an unordered_map named myMap that maps strings to integers. We want to check if the key "banana" exists in the map. We use the find() function to search for the key, and store the result in the iterator it.

We then compare it with myMap.end() (the end iterator of the unordered_map). If they are not equal, it means the key was found, so we print a message indicating that the key exists. Otherwise, if they are equal, it means the key was not found, so we print a message indicating that the key does not exist.

When you run this code, it will output:

Key 'banana' exists in the unordered_map.

This demonstrates that the key "banana" exists in the unordered_map.