简体   繁体   中英

Confusion with C++ STL container [] operator and default values

Consider the following code:

unordered_map<string, vector<string>> hashtable;
string s = "foo";
hashtable[s].push_back("bar");

This seems to work, but that means that in the third line, it is both adding a new entry to the hashtable by initializing a vector of strings at key "foo" as well as adding "bar" to this empty vector. My confusion is how come we don't have to explicitly initialize a vector like:

unordered_map<string, vector<string>> hashtable;
string s = "foo";
vector<string> vec;
vec.push_back("bar");
hashtable[s] = vec;

Adding to my confusion is when we are dealing with stuff like initializing arrays in C++, it is good to explicitly initialize the array like so:

int array[10] = {0);

This is required if we want to make sure the array is initialized with all values being 0 since without it, there could be garbage values stored in memory at the same place the array was initialized at. Going back to my first question with the hashtable, how do we know

hashtable[s].push_back("bar");

isn't pushing "bar" into a vector with garbage values?

I realize my question is not clear at all. Any clarifications with behaviour of [] operator and default values of STL containers is general would be appreciated.

  1. My confusion is how come we don't have to explicitly initialize a vector

This is the expected behavior of std::unordered_map::operator[] , which will perform an insertion with value-initialized mapped value if the key does not exist.

Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.

That means for hashtable[s].push_back("bar"); , a value-initialized std::vector (ie an empty std::vector ) will be inserted at first, then the vector will be returned by reference by std::unordered_map::operator[] . Then push_back("bar") is called on the vector (then its size becomes 1 and contains one element).

  1. isn't pushing "bar" into a vector with garbage values?

No, std::vector is not same as raw array, its size is dynamic. As explained above, the value-initialized std::vector is empty, its size is 0 , still doesn't contain any elements (and any "garbage values").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM