Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading