map<pair<double,double>,double> vectorDoubleMap;
vectorDoubleMap[ pair<double, double>(10, 10) ] = 1; //1.
vectorDoubleMap.insert( pair<double, double>(10, 10), 1); //2.
‘1.’ statement compile done, but ‘2.’ statement not compiled.
What’s the difference between these two statement?
map::inserttakes a single pair argument holding key and value, not key and value as separate arguments. If you pass a second argument, the first is an iterator used as a hint for alikely insertion position, whereas the second is still a pair.So you’d have to write one of these:
You can see how
make_pairmakes the syntax much more concise in this case. (As the numbers are entered as integer literals, integer pairs will be constructed at first, but there is a conversion constructor for pairs of one kind to another, so this is all right and will be converted to double as needed. The compiler might even optimize the integers away and directly use doubles in the code it generates.)If the key is not present in the map, the two statements will be equal in effect and similar in performance. If the key is already present, the
[…]=…form will overwrite it, whereas theinsert(…)form will keep the old value.Note that C++17 will likely offer two more ways to accomplish the same thing.
insert_or_assignis roughly equivalent to your first line, since it will overwrite existing values.try_emplaceis more like the second, since it won’t overwrite if the key is already present. The key benefit for both of these is that they accept arguments for a constructor, and construct the object in place. Which isn’t of much use fordouble, but might be useful for other objects which are hard to construct, copy or move. But still, the fact thattry_emplacetakes separate arguments and not a singlepairmakes that one a nice replacement for theinsertdiscussed above.