tush
tush

Reputation: 59

How to have set of struct using custom comparator function instead of operator overloading

I want to insert instances of structs into a set. I know that to do this the < operator has to be overloaded so that set can make a comparison in order to do the insertion.

Following program works perfectly.

#include <iostream>
#include<set>
using namespace std;

struct Node
{
    int x;
    int y;
};

  bool operator <( const Node &a,const Node &b)
{
    return a.x < b.x ||( a.x == b.x && a.y < b.y);
}

int main()
{
    set<Node> s;
    Node node;

    node.x = 1;
    node.y = 2;

    s.insert(node);

    node.x = 1;
    node.y = 0;

   s.insert(node);

   for( Node node : s)
       cout << node.x <<","<< node.y <<endl;
}

Output :

1,0
1,2

But if I want to use custom comparator function,instead of operator overloading I tried this way.

bool Comp( const Node &a,const Node &b)
{
    return a.x < b.x ||( a.x == b.x && a.y < b.y);
}

And in main() , I define set as this way.

set<Node, Comp> s; // error 

But I got following error :

type/value mismatch at argument 2 in template parameter list for ‘template<class _Key, class _Compare, class _Alloc> class std::set’   set<Node, Comp> s;

Can anyone explain, why there is a error ? How to rectify it ?

Upvotes: 0

Views: 1507

Answers (2)

Jarod42
Jarod42

Reputation: 217145

You might use function pointer:

bool Comp(const Node &lhs, const Node &rhs)
{
    return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y);
}

set<Node, bool (*)(const Node&, const Node&)> s(&Comp);

or even better functor (as comparator is fixed):

struct Comp
{
    bool operator() (const Node &lhs, const Node &rhs) const
    {
        return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y);
    }

};

set<Node, Comp> s;

Upvotes: 2

songyuanyao
songyuanyao

Reputation: 172894

The 2nd template parameter of std::set expects a type, but Comp is a function, not type. You could

// specify the function pointer type as the 2nd template argument
set<Node, decltype(&Comp)> s(&Comp);

Note that the function pointer is passed to the constructor here. Otherwise the default initialized comparison function pointer would be null pointer.

LIVE

Upvotes: 1

Related Questions