C++ Map Insert
Inserting into a map is faster using value_type than std::pair.
Here are four common ways to insert into a map:
std::map m;
- m[0] = 100;
- m.insert(std::pair<int, int>(0, 100));
- m.insert(std::make_pair(0, 100));
- m.insert(std::map<int, int>::value_type(0, 100));
The last one is the fastest. My benchmarks showed that inserting using value_type is 2-5% faster than using pair, depending on optimization flag. I missed this obvious part of C++ because its syntax is more complex than the other solutions. Terrible reason, but there it is.
Also, to state the obvious: m[0] = 100 is not equivalent to an insert. An insert will not overwrite any previous value. Surprised? So was I.
Source:
C++ reference: std::map::insert
Quote: "[T]he insertion operation checks whether each inserted element has a key equivalent to the one of an element already in the container, and if so, the element is not inserted, returning an iterator to this existing element"
Ches Koblents
October 9, 2012