Paul
Paul

Reputation: 65

Initializing map with greater comparator

I am confused as to why initializing map with std::less comparator works but std::greater does not.

The constructor I believe I am using is this one

explicit map( const Compare& comp,
              const Allocator& alloc = Allocator() );   

Code example:

typedef std::map<double, std::queue<something>> mydef;
auto t1 = mydef{std::less<double>()} // works
auto t2 = mydef{std::greater<double>()} // does not ( error: no matching constructor for initialization of 'mydef' .... )

Upvotes: 0

Views: 725

Answers (2)

eerorika
eerorika

Reputation: 238311

std::greater is a template. std::greater<T> is a type. The comparator is a template type argument of std::map.

std::map<double, std::queue<something>> uses the default comparator type that is std::less<double>. That is why you can instantiate the map using an instance of std:less but not any other comparator.

You need to specify the comparison object type in the instantiation of std::map template: std::map<double, std::queue<something>, std::greater<>>.

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 595827

Your need to take the definitions of Compare into account. It is taken from the map's template arguments:

template<
    class Key,
    class T,
    class Compare = std::less<Key>, // <-- here
    class Allocator = std::allocator<std::pair<const Key, T>>
> class map;

Thus making the constructor you want to call effectively this by default:

explicit map( const std::less<Key>& comp, const std::allocator<std::pair<const Key, T>>& alloc = std::allocator<std::pair<const Key, T>>() );

That is why only std::less works by default when you construct instances of mydef.

You need to change your declaration of mydef in order to use std::greater instead:

typedef std::map<double, std::queue<something>, std::greater<double>> mydef;
auto t1 = mydef{std::less<double>()}; // error: no matching constructor for initialization of 'mydef' ....
auto t2 = mydef{std::greater<double>()}; // works

Upvotes: 1

Related Questions