I have identified four different ways of inserting elements into a std::map:
std::map function;
function[0] = 42;
function.inse
First of all, operator[] and insert member functions are not functionally equivalent :
operator[] will search for the key, insert a default constructed value if not found, and return a reference to which you assign a value. Obviously, this can be inefficient if the mapped_type can benefit from being directly initialized instead of default constructed and assigned. This method also makes it impossible to determine if an insertion has indeed taken place or if you have only overwritten the value for an previously inserted keyinsert member function will have no effect if the key is already present in the map and, although it is often forgotten, returns an std::pair which can be of interest (most notably to determine if insertion has actually been done).From all the listed possibilities to call insert, all three are almost equivalent. As a reminder, let's have look at insert signature in the standard :
typedef pair value_type;
/* ... */
pair insert(const value_type& x);
So how are the three calls different ?
std::make_pair relies on template argument deduction and could (and in this case will) produce something of a different type than the actual value_type of the map, which will require an additional call to std::pair template constructor in order to convert to value_type (ie : adding const to first_type)std::pair will also require an additional call to the template constructor of std::pair in order to convert the parameter to value_type (ie : adding const to first_type)std::map::value_type leaves absolutely no place for doubt as it is directly the parameter type expected by the insert member function.In the end, I would avoid using operator[] when the objective is to insert, unless there is no additional cost in default-constructing and assigning the mapped_type, and that I don't care about determining if a new key has effectively inserted. When using insert, constructing a value_type is probably the way to go.