如何定义priority_queue,function或functor的比较?

时间:2015-05-12 18:06:02

标签: c++ comparison priority-queue functor

我需要在C ++中存储priority_queue的自定义对象。我应该使用二元函数还是函子?每种方法的优点还是劣势?谢谢!

1 个答案:

答案 0 :(得分:0)

您可以为您的班级定义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();
    }
}

Output

a: 5 b: 2
a: 4 b: 1
a: 3 b: 4
a: 2 b: 7

您还可以定义operator>并将Compare的模板参数从std::greater<Foo>传递为<functional>,以使队列按最小顺序而非最大值。

相关问题