How to create a std::set with custom comparator in C++?(如何在 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 中使用自定义比较器创建 std::set?


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01