The Operations for Reading and Writing Single Elements for C++ Standard Library Maps -- Raymond Chen

RaymondChen_5in-150x150.jpgSome 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.
2024-11-21_13-35-17.png

In the table above, key is the map key, value is the mapped type, and params are parameters to the mapped type constructor.

Note that insert and the first emplace¹ 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.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.