The Code:
boost::unordered_map<int, boost::unordered_map<int, float>> map;
{
boost::unordered_map<int, float> h;
h.insert(make_pair(1, 0.5));
map.insert(make_pair(5, h));
}
{
boost::unordered_map<int, float> h = map[5];
h.insert(make_pair(2, 0.6));
map.insert(make_pair(5, h));
}
cout << map[5].size() << endl;
Why the output is 1 not 2?
And when i use boost::unordered_map* > instead, then everything works well.
Can anyone help me?
Here’s what happens in the second block of code:
h = map[5]creates a copy of the inner map.h.insert(...)adds a value to the copy of the inner map.map.insert(...)does nothing. unordered_map::insert inserts an element to the map if and only if there is no element in the map with an equivalent key. But the key 5 is already present, and so no insertion happens. You can confirm this by checking that the boolean portion of the return value from the insert call is false.At the end of the block, the copied map is discarded, and the original inner map, with a single value, remains in
map. As a result, you get the output of map[5].size()==1.But why do we get an output of 2 if the value type of the inner map is set to a pointer,
boost::unordered_map<int, float>*? The second block of code would do this:h = map[5]will get a pointer to the inner map inserted intomap.h.insert(...)adds a value to the inner map directly — not into a copy. At this point, map[5].size()==2 already.map.insert(...)still does nothing. But there’s no need to — the inner map was already modified in place.