C++ map insert -- replace existing element

Viewed 265

So I have a map of strings to objects, and I want to maintain the objects in alphabetical order. At first I did the following.

const auto &insertItr = m.insert(std::pair(text, objectPtr));

Thus, when I am inserting into the map, I want the insertion index, which I can get by subtracting the returned iterator from m.begin(). However, if the key text already exists in the map, then the object is not replaced like I intend, and the iterator instead points to the already existing object, which is not what I want.

While I could do

m[text] = objectPtr;
const auto &insertItr = m.find(text);

or

m.erase(m.find(text));
const auto &insertItr = m.insert(std::pair(text, objectPtr));

That is 2 operations, and I was wondering if there was 1 operation which would achieve the same result.

Thanks!

2 Answers

You are looking for std::map::insert_or_assign

auto insertItr = m.insert_or_assign(text, objectPtr).first;

This function returns both the iterator, and a bool indicating whether an insertion occurred.

If you can compile with C++17 you can use std::map::insert_or_assign

const auto &insertItr = m.insert_or_assign(text, objectPtr);
Related