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?


- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- Stroustrup 的 Simple_window.h 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- C++ 协变模板 2021-01-01