How to Find with Hash Map

c++11 containers intermediate

There’s two methods to find an element in a std::unordered_map: the find() method and the square bracket operator([]). The find() method returns an iterator to a key-value pair, meaning an iterator to std::pair<Key, Value>. Because it’s an iterator to a pair, you can access the key with it->first and the value with it->second. If nothing was found, the end() iterator is returned from the unordered_map.

#include <unordered_map>
#include <string>
#include <iostream>

int main() {
  std::unordered_map<int, std::string> statusCodes{
    {200, "Success"},
    {404, "This is not the page you're looking for"},
  };

  auto it = statusCodes.find(200);
  if (it != statusCodes.end()) {
    std::cout << it->first << ": " << it->second << "\n";
  } else {
    std::cout << "No such status code.\n";
  }
  
  it = statusCodes.find(1000);
  if (it != statusCodes.end()) {
    std::cout << it->first << ": " << it->second << "\n";
  } else {
    std::cout << "No such status code.\n";
  }
}
200: Success
No such status code.

The square bracket operator([]) returns a non-const reference to a key’s value, meaning a Value&. Because this operator must return a reference it cannot represent the “not found” case that find() can with end(). This means if the square bracket operator([]) fails to find the element it default constructs a new element and returns a reference to that! This can sometimes be useful but be careful as it’s usually unintended. Here’s an example:

#include <unordered_map>
#include <string>
#include <iostream>

int main() {
  std::unordered_map<int, std::string> statusCodes{
    {200, "Success"},
    {404, "This is not the page you're looking for"},
  };

  // This creates a new status code 503 with an empty description!
  std::string description = statusCodes[503];
  std::cout << description << "\n";

  // This constructs a new key-value!
  statusCodes[201] = "Oops, we meant 200!";
  std::cout << statusCodes[201] << "\n";

  // The map now has 4 elements in it!
  std::cout << statusCodes.size() << "\n";
}
Oops, we meant 200!
4

For more C++ By Example, click here.