user1971455
user1971455

Reputation: 433

How to declare set with pointer type comparator in C++?

I have this struct for general lessThan comparison of pointers:

template < class ptype > 
struct lessThan : public binary_function < ptype *, ptype *, bool >
{
    bool operator() (ptype *lhs, ptype *rhs) { return lhs->key() < rhs->key(); }
};

Suppose I want to create a set of object pointers using this lessThan comparator. What would be the proper syntax when declaring the set? I'm thinking something like this:

set <Object *, lessThan> mySet;

or more like a function pointer:

set <Object *, lessThan<Object>()> mySet;

...but I can't get it to compile. Any advice?

Upvotes: 3

Views: 165

Answers (1)

Shoe
Shoe

Reputation: 76240

The template class std::set takes as second template argument a type of the concept Compare. So in your case the type would be lessThan<Object>.

This would make the correct declaration be:

std::set<Object*, lessThan<Object>> x;

Live demo

Your first attempt was incorrect because lessThan is not a type, it's a class template. Your second attempt was incorrect because lessThan<Object>() is a parsed as a function returning lessThan<Object>.

Upvotes: 4

Related Questions