Error Handling in std::unordered_map

How can I handle errors and exceptions when using std::unordered_map?

When working with std::unordered_map, there are a few common errors and exceptions you may encounter. Here are some ways to handle them:

Key Not Found

When trying to access a key that doesn't exist in the map using the [] operator or the at() function, you can handle it in two ways:

  • Use the [] operator and check if the key exists before accessing the value. If the key doesn't exist, it will be inserted with a default-constructed value.
  • Use the at() function, which throws a std::out_of_range exception if the key is not found. Catch the exception to handle the error.
#include <iostream>
#include <string>
#include <unordered_map>

int main() {
  std::unordered_map<std::string, int> map{
    {"A", 1}, {"B", 2}};

  // Using [] operator
  if (map.count("C") == 0) {
    std::cout << "Key 'C' not found\n";
  } else {
    int value = map["C"];
  }

  // Using at() function
  try {
    int value = map.at("D");
  } catch (const std::out_of_range& e) {
    std::cout << "Key 'D' not found: "
      << e.what() << '\n';
  }
}
Key 'C' not found
Key 'D' not found: invalid unordered_map<K, T> key

Insertion Failure

When inserting a new element using insert() or emplace(), the operation may fail if an element with the same key already exists. You can check the return value of these functions to handle the failure.

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

int main() {
  std::unordered_map<std::string, int> map{
    {"A", 1}, {"B", 2}};

  // Insertion using insert()
  auto result1 = map.insert({"A", 3});
  if (!result1.second) {
    std::cout << "Insertion failed: "
      "key 'A' already exists\n";
  }

  // Insertion using emplace()
  auto result2 = map.emplace("C", 3);
  if (!result2.second) {
    std::cout << "Insertion failed: "
      "key 'C' already exists\n";
  }
}
Insertion failed: key 'A' already exists

Memory Allocation Failure

In rare cases, memory allocation for new elements may fail due to insufficient memory. This will throw a std::bad_alloc exception. Catch the exception to handle the error gracefully.

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

int main() {
  try {
    std::unordered_map<std::string, int> map;
    // Simulate memory allocation failure
    throw std::bad_alloc();
  } catch (const std::bad_alloc& e) {
    std::cout << "Memory allocation failed: "
      << e.what() << '\n';
  }
}
Memory allocation failed: bad allocation

By anticipating and handling these common errors and exceptions, you can write more robust and reliable code when using std::unordered_map. It's important to consider the specific requirements and error handling strategies of your application to ensure appropriate error handling and recovery.

Hash Maps using std::unordered_map

Creating hash maps using the standard library's std::unordered_map container

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

emplace() vs insert() when using std::unordered_map
When should I use emplace() instead of insert() for std::unordered_map?
std::unordered_map Performance Considerations
What factors affect the performance of std::unordered_map operations?
Requirements for Custom Key Types in std::unordered_map
What are the requirements for using a custom type as the key in std::unordered_map?
std::unordered_map vs std::map - When to Use Each
When should I use std::unordered_map instead of std::map?
Handling Hash Collisions in std::unordered_map
How does std::unordered_map handle hash collisions?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant