Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why std::map overloaded operator < does not use the Compare

Tags:

c++

stl

From http://www.cplusplus.com/reference/map/map/operators/ I noticed:

"Notice that none of these operations take into consideration the internal comparison object of either container, but compare the elements (of type value_type) directly."

this is to say that the overloaded operator "<" is not using the Compare in its declaration (refer to http://www.cplusplus.com/reference/map/map/)

std::map
template < class Key,                                     // map::key_type
           class T,                                       // map::mapped_type
           class Compare = less<Key>,                     // map::key_compare
           class Alloc = allocator<pair<const Key,T> >    // map::allocator_type
           > class map;

where the Compare is

Compare: A binary predicate that takes two element keys as arguments and returns a bool. The expression comp(a,b), where comp is an object of this type and a and b are key values, shall return true if a is considered to go before b in the strict weak ordering the function defines. The map object uses this expression to determine both the order the elements follow in the container and whether two element keys are equivalent (by comparing them reflexively: they are equivalent if !comp(a,b) && !comp(b,a)). No two elements in a map container can have equivalent keys. This can be a function pointer or a function object (see constructor for an example). This defaults to less<T>, which returns the same as applying the less-than operator (a<b). Aliased as member type map::key_compare.

I don't quite understand it, why not just use Compare in the "<" operator?

like image 747
athos Avatar asked Jan 06 '15 13:01

athos


1 Answers

Compare is for comparing key_type. The map's < operator is actually comparing mapped_type value_type, not key_type, so Compare would not be applicable. value_type is the pair of key_type and mapped_type.

To be honest, though, I think giving map an operator< in the first place is a case of operator overloading gone too far. It's not immediately obvious what is means to say one map is "less than" another. If you want lexigraphical_compare, I'd recommend calling it directly, or at least documenting in your code what your map comparison means.

like image 127
Joel Avatar answered Nov 15 '22 21:11

Joel