如何定义Priority_queue,函数或函子的比较
How to define comparison for priority_queue, function or functor?
我需要在C 中存储具有Priority_queue的自定义对象。我应该使用二进制功能还是函数?每种方法有任何优势或缺点吗?谢谢!
您可以定义类的operator<
,然后将定义std::less
,而您根本不需要通过函数。
#include <iostream>
#include <queue>
class Foo
{
public:
Foo(int _a, int _b) : a{_a}, b{_b} {}
bool operator<(const Foo& other) const
{
return a < other.a || (a == other.a && b < other.b);
}
int GetA() const { return a; }
int GetB() const { return b; }
private:
int a;
int b;
};
int main()
{
std::priority_queue<Foo> x;
x.emplace(3,4);
x.emplace(4,1);
x.emplace(5,2);
x.emplace(2,7);
while (!x.empty())
{
Foo foo = x.top();
std::cout << "a: " << foo.GetA() << " b: " << foo.GetB() << std::endl;
x.pop();
}
}
输出
a: 5 b: 2
a: 4 b: 1
a: 3 b: 4
a: 2 b: 7
您还可以定义operator>
并将Compare
的模板参数从<functional>
传递为std::greater<Foo>
,以最低顺序而不是最大值。
相关文章:
- C++自定义比较函数
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- C++模板函数,用于比较任何无符号整数和有符号整数
- 函数类作为比较器
- 什么是自定义比较器以及如何在 C++ 的排序函数中使用它?
- 没有默认构造函数作为模板参数的自定义比较器
- std::max() 函数与定点实现的比较中的问题
- 如何比较两个函数的速度和性能
- 对没有比较器或λ函数的向量进行排序?
- 使用迭代器的自定义比较器函数
- 隐式转换为比较函数对象(函子)用于 std::sort 而不是 std::map?
- 比较 n 女王的 next_permutation 函数
- 用于基于成员字段或函数创建比较器的快捷方式
- 为什么 std::stable_sort() 的比较函数的参数必须是设置常量?
- 为什么在类或结构中传递自定义比较器函数?
- 浮点数比较为什么没有相等的函数
- 通过默认复制构造函数比较 C++ 字符串是否会影响性能,原因为何?
- 为什么函数比较器不像在排序中那样在优先级队列中工作?
- c++ STL集合的比较函数:比较函数可以是类的成员函数吗?
- 联合值的单函数比较