C++ priority queue in ascending order by specific method for unique pointers to objects

2814 views c++
6

I have a class called Foo and every Foo object has a method called yVal. WHat I wanted was a priority Queue of Foo objects in ascending order of Foo.yVal()

I overloaded the operator> and operator< in Foo to this:

   bool operator> (const Foo &f){
        return yVal() > f.yVal();
   }

   bool operator< (const Foo &f){
        return yVal() < f.yVal();
   }

And So I have the following code:

priority_queue<unique_ptr<Foo>, vector<unique_ptr<Foo>>, greater<unique_ptr<Foo>> > Queue;

But that was not Sorting the priority queue in ascending order of Foo.yVal(), instead it was just sorting them in some unknown random order. I put a cout statement in the operator> and operator< and they weren't even being called. So I tried doing this with a lambda instead:

auto cmp = [](Foo left, Foo right) {return left.xVal() > right.xVal();};
priority_queue<unique_ptr<Foo>, vector<unique_ptr<Foo>>, decltype(cmp) > Queue(cmp);

But this gave me the error of "non-static data member declared auto" error.

I would ideally like to get this working with the greater<> and operator overloading, if not can someone please tell me what I am doing wrong with the lambda (not too familiar with lambdas and would like to avoid them if possible).

answered question

1 Answer

12

You are using this comparator: greater<unique_ptr<Foo>>, which is not the same as using greater<Foo>.

Create a functor for your comparison operators, and use it as the sort key, something like:

struct Comparator
{
    bool operator()(const Foo &f1, const Foo &f1){
        return f1.yVal() < f2.yVal();
    }
};

posted this

Have an answer?

JD

Please login first before posting an answer.