首页 > 解决方案 > 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 ?

标签: c++c++17

解决方案


您可以使用函数指针:

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);

甚至更好的仿函数(因为比较器是固定的):

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;

推荐阅读