mardi 29 mars 2016

modifying the value of a complex type in a C++ unordered_map

I am trying to understand why using operator[] on unordered_map in C++ gives me different results when I attempt to modify the value using [] directly vs. store the value in a temporary object. Here's an example:

unordered_map<int,vector<int>> map;
map.emplace(0, vector<int>(10, 1) );

map[0][0] = 2; // this works
cerr << map[0][0] << endl; // prints out 2 - as expected

auto foo = map[0];
foo[1] = 3; // this does not work -- the value in map[0][1] is still 1
cerr << map[0][1] << endl; // prints out 1, expected: 3

My understanding was that map[0] should return the reference to the associated value, not its copy, but it seems that foo is a copy since changes to foo are transient. What am I missing?

Aucun commentaire:

Enregistrer un commentaire