如何定义Priority_queue,函数或函子的比较

How to define comparison for priority_queue, function or functor?

本文关键字:函数 比较 queue 何定义 定义 Priority      更新时间:2023-10-16

我需要在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>,以最低顺序而不是最大值。