C++ 如何使用自定义比较器函数而不是运算符重载创建一组结构

C++ 如何使用自定义比较器函数而不是运算符重载创建一组结构,c++,c++17,C++,C++17,我想在集合中插入结构的实例。我知道要做到这一点,

我想在集合中插入结构的实例。我知道要做到这一点,<运算符必须重载,以便set可以进行比较,以便进行插入

下面的程序运行良好

#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;
}
#包括
#包括
使用名称空间std;
结构体类型
{
int x;
int-y;
};

bool操作符的第二个模板参数需要一个类型,但
Comp
是一个函数,而不是类型。你可以

// specify the function pointer type as the 2nd template argument
set<Node, decltype(&Comp)> s(&Comp);
//将函数指针类型指定为第二个模板参数
设置s(&Comp);
注意,函数指针在这里传递给构造函数。否则,默认初始化的比较函数指针将是空指针


的第二个模板参数需要一个类型,但
Comp
是一个函数,而不是类型。你可以

// specify the function pointer type as the 2nd template argument
set<Node, decltype(&Comp)> s(&Comp);
//将函数指针类型指定为第二个模板参数
设置s(&Comp);
注意,函数指针在这里传递给构造函数。否则,默认初始化的比较函数指针将是空指针


您可以使用函数指针:

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

bool Comp(常量节点和左侧、常量节点和右侧)
{
返回标准::tie(左S.x,左S.y)<标准::tie(右S.x,右S.y);
}
设置s(&Comp);
或者更好的函子(因为比较器是固定的):

struct Comp
{
布尔运算符()(常量节点和左侧、常量节点和右侧)常量
{
返回标准::tie(左S.x,左S.y)<标准::tie(右S.x,右S.y);
}
};
设置s;

您可以使用函数指针:

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

bool Comp(常量节点和左侧、常量节点和右侧)
{
返回标准::tie(左S.x,左S.y)<标准::tie(右S.x,右S.y);
}
设置s(&Comp);
或者更好的函子(因为比较器是固定的):

struct Comp
{
布尔运算符()(常量节点和左侧、常量节点和右侧)常量
{
返回标准::tie(左S.x,左S.y)<标准::tie(右S.x,右S.y);
}
};
设置s;
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;