Reputation: 3839
I have a boost::unordered_map<std::string, std::string>
, and whenever I add a Key/Value pair to the map for which there already exists a previous Key in the map, I want the old value to be deleted and replaced with the new value. Also, since my compiler and libraries support emplace()
, I'd like to use that (assuming that it may eliminate the construction of a temporary).
What is the most efficient way to program this? I'm finding the Boost doc a little hard to understand here.
My compiler is g++ 4.4.7 with -std=g++0x
Upvotes: 3
Views: 1061
Reputation: 304182
I think you just want to use operator[]
here. Stuff like emplace
and insert
won't overwrite the value for you if it's already there, so just:
map[key] = newVal;
Works regardless of whether key
existed in the map before or not.
Upvotes: 1
Reputation: 137960
Use the optional insertion point hint (obtained by calling find()
first):
iterator insert(const_iterator hint, const value_type& obj);
In the case of emplace
, it's not a same-named overload:
template <class... Args> iterator emplace_hint(const_iterator position, Args&&... args);
I got these signatures from the C++14 draft standard because that's what I have handy, but they should date back to Boost if it has emplace
, and otherwise you should update your compiler anyway. There's no sense in using such a shaky platform as Boost with -std=c++0x
on an old compiler.
If you aren't replacing a preexisting entry, find
will not return a useful hint.
If you are replacing an entry, you might as well just assign the new value to the existing object.
So, the hint is only useful in the case you actually want to erase
the old object and insert
a new one.
Upvotes: 1