Why doesn't C++ unordered_maps with vector values require vector initialization

I normally like to program in Python, and I noticed in a Leetcode problem solution written in C++ that the unordered_map<string, vector<string>> did not require the vectors to be initialized before they were pushed to.

For example, the something like the following code would run successfully in C++

unordered_map<string, vector<string>> example;

example["example_key"].push_back("example_elem");

But in Python, similar code would return a KeyError since the list associated with the key has not been initialized

example = {}

example["example_key"].append("example_elem")

Why does the unordered_map not require the vector to be initialized before something is pushed to it?

>Solution :

https://en.cppreference.com/w/cpp/container/unordered_map/operator_at

std::unordered_map<...>::operator[] Inserts a value_type object constructed in-place… if the key does not exist. This function is equivalent to return this->try_emplace(key).first->second;. (since C++17)

Note that maps also offer an at member which does the bounds checking.

https://en.cppreference.com/w/cpp/container/unordered_map/at

std::unordered_map<...>::at Returns a reference to the mapped value of the element with key equivalent to key. If no such element exists, an exception of type std::out_of_range is thrown.

Leave a Reply