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

查看:62
本文介绍了如何在 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>

推荐答案

方法一:使用函子

编写一个重载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;

方法二:使用函数指针

假设 compare 是你要使用的函数:

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

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

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