Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overload of std::unordered_map::insert

Tags:

c++

c++11

Would you teach me why both

std::unordered_map::insert(const value_type&)

and

template<class P> std::unordered_map::insert(P&&)

exist in the standard?

I think that insert(P&&) can serve as insert(const value_type&).

like image 842
Mitsuru Kariya Avatar asked Feb 06 '13 04:02

Mitsuru Kariya


1 Answers

Both of these overloads

auto std::unordered_map::insert(const value_type&) -> ...

template<class P>
auto std::unordered_map::insert(P&&) -> ...

have their advantages and neither can fully replace the other. The first one seems like a special case of the second one since P might be deduced to be const value_type&. The nice thing about the 2nd overload is that you can avoid unnecessary copies. For example, in this case:

mymap.insert(make_pair(7,"seven"));

Here, the result of make_pair is actually a pair<int, const char*> whereas value_type might be pair<const int, string>. So, instead of creating a temporary value_type object and copying it into the container, we have the chance of directly creating the value_type object into the map by converting the argument and/or moving its members.

On the other hand, it would be nice if this worked as well:

mymap.insert({7,"seven"});

But this list is actually not an expression! The compiler can't deduce P for the second overload because of that. The first overload is still viable since you can copy-initialize a pair<const int,string> parameter with such a list.

like image 129
sellibitze Avatar answered Oct 06 '22 01:10

sellibitze