如何在C ++中使用自定义比较器创建std :: set? [英] How to create a std::set with custom comparator in C++?

查看:135
本文介绍了如何在C ++中使用自定义比较器创建std :: set?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I create a set of pairs, the elements of which (the pairs) are sorted with a custom bool function? I write

set <pair<int,int>,compare> myset;

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

and get error : Type/value mismatch at argument 2, expected a type, got "compare"

我将比较定义为

bool compare(pair <int,int> g1, pair <int,int> g2)
{
    return (g1.second-g1.first > g2.second-g2.first);
}

,当然

#include <vector>
#include <set>


推荐答案

方法1:使用functor



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

Method 1: use functor

Write a class that overloads the operator()so it can be called like a function:

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

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

Then, you can use the class name as the type parameter

set<pair<int,int>, compare> myset;



方法2:使用函数指针



假设比较是您要使用的函数:

Method 2: use function pointer

Assuming compare is the function you want to use:

set<pair<int,int>, bool(*)(const pair<int,int> &lhs, 
                           const pair<int,int> &rhs)
   > myset(&compare);

这篇关于如何在C ++中使用自定义比较器创建std :: set?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆