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 is0
. - 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:
- When you access
freq[6]
and the key6
does not exist, theunordered_map
inserts it with a default value of0
(because the value type isint
). - After that, if you assign
freq[6] = 10
, the key6
now maps to10
.
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.