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&)
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With