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?
https://en.cppreference.com/w/cpp/container/unordered_map/operator_at
std::unordered_map<...>::operator[]
Inserts avalue_type
object constructed in-place... if thekey
does not exist. This function is equivalent toreturn 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 tokey
. If no such element exists, an exception of typestd::out_of_range
is thrown.