A Simplified Overview of Ways to Add or Update Elements in a std::map -- Raymond Chen

RaymondChen_5in-150x150.jpgThe std::map subscript operator ([]) is a convenient but sometimes dangerous feature, as it can create unintended default-constructed entries. By understanding the behavior of various map insertion and lookup methods—such as insert, emplace, try_emplace, and insert_or_assign—developers can write more efficient and predictable code while avoiding unnecessary key-value creations and duplicate lookups.

A Simplified Overview of Ways to Add or Update Elements in a std::map

by Raymond Chen

From the article:

Some time ago, I mentioned how the std::map subscript operator is a dangerous convenience. In that article, I linked to an overview of the insertion emplacement methods, but I’m going to recapture the essential points in a table.¹

In the table below, the discussion of “consumed” or “not consumed” refers to the case that v is an rvalue reference like std::move(something).

stdmap-chen.png

We can reorganize the table by effect.
stdmap2-chen.png
Exercise: Why are the bottom left two boxes blank?

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.