Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector as map value, insert new key and push back immediately c++

Tags:

c++

dictionary

Does this work?

map<string, vector<int>> mymap;
mymap["bob"].push_back(1);
mymap["joe"].push_back(3);
mymap["joe"].push_back(12);

Or do I have to do this?

map<string, vector<int>> mymap;
if (mymap.find("bob") == mymap.end()) {
    vector<int> vec;
    mymap["bob"] = vec;
    mymap["bob"].push_back(1);
}
else {
    mymap["bob"].push_back(1);
}
...

Basically the question is whether or not mymap["bob"] creates the vector as its mapped value, or if I have to create a vector myself and add it into the map for new keys.

like image 609
Zachary Scott Lohner Avatar asked Sep 01 '25 22:09

Zachary Scott Lohner


2 Answers

Short answer: your code is fine.

std::map::operator[]

mapped_type& operator[] (const key_type& k);

If k matches the key of an element in the container, the function returns a reference to its mapped value.

If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).

A similar member function, map::at, has the same behavior when an element with the key exists, but throws an exception when it does not.

source: C++ Reference

Considering your second line, for example:

mymap["bob"].push_back(1);

mymap doesn't have a key "bob", so it creates one and returns a reference to a default-constructed (i.e. empty) vector<int> associated with that key.

You then push_back(1) to that vector. You could access mymap["bob"] again, and you'll get a reference to that vector, containing the single element 1.

like image 133
Toby Speight Avatar answered Sep 03 '25 13:09

Toby Speight


map<string, vector<int>> mymap;
mymap["bob"].push_back(1);

should work. map::operator[] inserts an item for the given key if one doesn't already exist.

From http://en.cppreference.com/w/cpp/container/map/operator_at

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.

like image 30
R Sahu Avatar answered Sep 03 '25 11:09

R Sahu