0

I need to store customized objects with priority_queue in C++. Should I use binary function or functor? Any advantage or disadvantage for each approach?? Thanks!

Sarah
  • 453
  • 7
  • 16
  • 3
    Definitely prefer a functor. It's a lot easier for the compiler to inline. – T.C. May 12 '15 at 18:07
  • 1
    see also: http://stackoverflow.com/questions/6451866/why-use-functors-over-functions – NathanOliver May 12 '15 at 18:10
  • If the sorting of your objects (in terms of operator <) is well defined use a freestanding operator <, otherwise provide a predicate (functor). –  May 12 '15 at 18:13

1 Answers1

0

You can define the operator< for your class, then std::less will be defined and you don't need to pass a functor at all.

#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

You can also define operator> and pass the template argument for Compare as std::greater<Foo> from <functional> to have the queue in minimum order instead of maximum.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218