Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL map - insert or update

Tags:

c++

stl

I have a map of objects and I want to update the object mapped to a key, or create a new object and insert into the map. The update is done by a different function that takes a pointer to the object (void update(MyClass *obj))

What is the best way to "insert or update" an element in a map?

like image 404
CodeJunkie Avatar asked May 07 '10 06:05

CodeJunkie


People also ask

Does map insert overwrite?

map. insert() will only insert elements into the container if it doesn't already contain any elements, so this will ignore the later value elements assigned to it.

How do you update a map in C++?

C++ map update – Simple program example to update value in map. To update an existing value in the map, first we will find the value with the given key using map::find() function. If the key exists, then will update it with new value.

What does insert return in map?

map insert() in C++ STL Return Value: The function returns a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the element with an equivalent key in the map.


2 Answers

The operator[]    

like image 104
Terry Mahaffey Avatar answered Sep 29 '22 03:09

Terry Mahaffey


With something like the following snippet:

std::map<Key, Value>::iterator i = amap.find(key);

if (i == amap.end())
    amap.insert(std::make_pair(key, CreateFunction()));
else
    UpdateFunction(&(i->second));

If you want to measure something that might improve performance you might want to use .lower_bound() to find where an entry and use that as a hint to insert in the case where you need to insert a new object.

std::map<Key, Value>::iterator i = amap.lower_bound(key);

if (i == amap.end() || i->first != key)
    amap.insert(i, std::make_pair(key, CreateFunction()));
                                       // Might need to check and decrement i.
                                       // Only guaranteed to be amortized constant
                                       // time if insertion is immediately after
                                       // the hint position.
else
    UpdateFunction(&(i->second));
like image 29
CB Bailey Avatar answered Sep 29 '22 04:09

CB Bailey