Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::map assign its comparator?

Is std::map copy assignment (in style map1 = map2;) required to copy comparator of map2 to map1?

I have tested that actual implementations do that. I am more interested about where in C++ standard it is specified.

like image 838
Öö Tiib Avatar asked Jul 20 '17 14:07

Öö Tiib


People also ask

Can we use comparator with map in C++?

Method 2 – using the set of pairs The idea is to insert all the (key-value) pairs from the map into a set of pairs that can be constructed using a comparator function that orders the pairs according to the second value. Multimap is similar to a map with an addition that multiple elements can have the same keys.

Can we use comparator in map?

The default comparator for map sorting is less. Comparator is a type whose name is the third argument of the map declaration, of the map template specialization. This type can be a struct or a class, whose possibly only member, is a custom operator definition.

How does std::map work?

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare . Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees.

What is std::map used for?

If you mean std::map , it stores pairs of values. In each pair, the first value is called the key, and can be used to quickly look up the associated other value.


1 Answers

If we look at [associative.reqmts]/12 we have

When an associative container is constructed by passing a comparison object the container shall not store a pointer or reference to the passed object, even if that object is passed by reference. When an associative container is copied, either through a copy constructor or an assignment operator, the target container shall then use the comparison object from the container being copied, as if that comparison object had been passed to the target container in its constructor.

emphasis mine

So, in your example, map1 will get a copy of map2's comparator.

like image 89
NathanOliver Avatar answered Oct 31 '22 06:10

NathanOliver