如何在C++中使用自定义比较器创建std :: set?

man*_*smi 1 c++ set comparator std-pair

如何创建一组对,其中的元素(对)使用自定义bool函数进行排序?我写

set <pair<int,int>,compare> myset;
Run Code Online (Sandbox Code Playgroud)

并得到错误:参数2处的类型/值不匹配,预期类型,得到"比较"

我把"比较"定义为

bool compare(pair <int,int> g1, pair <int,int> g2)
{
    return (g1.second-g1.first > g2.second-g2.first);
}
Run Code Online (Sandbox Code Playgroud)

而且当然

#include <vector>
#include <set>
Run Code Online (Sandbox Code Playgroud)

her*_*tao 6

方法1:使用仿函数

编写一个重载的类,operator()以便可以像函数一样调用它:

struct compare {
    bool operator() (const pair<int,int> &lhs, const pair<int,int> &rhs) const{
         return (lhs.second-lhs.first > rhs.second-rhs.first);
    }
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用类名作为类型参数

set<pair<int,int>, compare> myset;
Run Code Online (Sandbox Code Playgroud)

方法2:使用函数指针

假设compare您要使用的功能:

set<pair<int,int>, bool(*)(const pair<int,int> &lhs, 
                           const pair<int,int> &rhs)
   > myset(&compare);
Run Code Online (Sandbox Code Playgroud)