Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map::insert change in C++17

I see that the insert method of std::map and std::unordered_map is going to change from

template<class P> std::pair<iterator,bool> insert(P&& value); (C++11)

to

std::pair<iterator,bool> insert(value_type&& value);  (C++17)

However, for these containers, value_type is std::pair<A const, int>. Two questions here:

  1. Why this change? What is the upside?
  2. How is this going to work to move a key on insertion? The C++11 version accepts anything (the constraint on P is default_constructible<value_type, P&&>), then std::pair<A, int> - which is most of the time the type of this argument as it is the one returned by std::make_pair - and can call the move constructor of A. But in the C++17 version, this argument is casted to value_type, where A is const, then non-movable. A has to be copied, if I am not overlooking something. Or does C++17 change anything on that side too?

Thanks!

like image 786
AntiClimacus Avatar asked Sep 12 '16 22:09

AntiClimacus


People also ask

Can I change value in map 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 is the complexity of std::map :: insert () method?

Its time complexity is O(logN). insert( ): insert a single element or the range of element in the map. Its time complexity is O(logN), when only element is inserted and O(1) when position is also given.

What does std::map insert return?

std::map::insert succeeds when it inserts the new element, otherwise it returns an iterator to an already existing element.

Does C++ map insert overwrite?

Why C++ map. insert() doesn't overwrite - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.


1 Answers

An additional non-template overload to insert was added in C++17.

Such an overload has the advantage that it permits .insert( { {key}, {value, args} } ) syntax -- {} based construction. template arguments cannot be passed {} based construction instructions without an explicit type.

like image 139
Yakk - Adam Nevraumont Avatar answered Oct 06 '22 03:10

Yakk - Adam Nevraumont