The Operations for Reading and Writing Single Elements for C++ Standard Library Maps -- Raymond Chen
Some time ago, I noted that the std::map
subscript operator is an attractive nuisance. It is the most convenient syntax, but is not often what you actually want.
The Operations for Reading and Writing Single Elements for C++ Standard Library Maps
by Raymond Chen
From the article:
I’ve broken down the various std::map
lookup and update operations into a table so you can choose the best one for your situation.
In the table above,
key
is the map key,value
is the mapped type, andparams
are parameters to the mapped type constructor.Note that
insert
and the firstemplace
¹ take a value which is discarded if it turns out that the key already exists. This is undesirable if creating the value is expensive.One frustrating scenario is the case where the mapped type’s default constructor is not the constructor you want to use for
operator[]
, or if you want the initial mapped value to be the result of a function call rather than a constructor. Here’s something I sort of threw together.