简体   繁体   中英

Efficiently inserting or updating in boost::unordered_map

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

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.


Caveat

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM