The difference between insert()
and operator[]
has already been well explained in the other answers. However, new insertion methods for std::map
were introduced with C++11 and C++17 respectively:
emplace()
as also mentioned in einpoklum's comment and GutiMac's answer.insert_or_assign()
and try_emplace()
.Let me give a brief summary of the "new" insertion methods:
emplace()
: When used correctly, this method can avoid unnecessary copy or move operations by constructing the element to be inserted in place. Similar to insert()
, an element is only inserted if there is no element with the same key in the container.insert_or_assign()
: This method is an "improved" version of operator[]
. Unlike operator[]
, insert_or_assign()
doesn't require the map's value type to be default constructible. This overcomes the disadvantage mentioned e.g. in Greg Rogers' answer.try_emplace()
: This method is an "improved" version of emplace()
. Unlike emplace()
, try_emplace()
doesn't modify its arguments (due to move operations) if insertion fails due to a key already existing in the map.For more details on insert_or_assign()
and try_emplace()
please see my answer here.