Unordered Containers std::unordered_map in C++

In C++, when you access an element of an unordered_map using the [] operator, such as freq[6], if the key 6 does not exist in the map, the unordered_map will automatically insert the key with a default value.

The default value depends on the type of the values stored in the map:

  • For numeric types (like int), the default value is 0.
  • For other types, the default constructor of that type is used (e.g., for std::string, it's an empty string).
#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_map<int, int> freq;

    // Access a key that does not exist in the map
    std::cout << "freq[6]: " << freq[6] << std::endl; // Output will be 0

    // Now, the key 6 has been inserted with a value of 0
    freq[6] = 10;
    std::cout << "Updated freq[6]: " << freq[6] << std::endl; // Output will be 10

    return 0;
}

Explanation:

  1. When you access freq[6] and the key 6 does not exist, the unordered_map inserts it with a default value of 0 (because the value type is int).
  2. After that, if you assign freq[6] = 10, the key 6 now maps to 10.

If you don't want to insert the key when it doesn't exist, you can use the .find() method to check for the existence of the key:

if (freq.find(6) == freq.end()) {
    std::cout << "Key 6 does not exist in the map." << std::endl;
} else {
    std::cout << "Key 6 exists with value: " << freq[6] << std::endl;
}

This way, you can avoid inserting a key with a default value.