Jump to content

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


Horizon

Recommended Posts

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.

View the full article

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...