Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Lets say I have the a class called MyClass and every MyClass object has a method called xVal. What I want is a priority queue of MyClass objects sorted in ascending order of MyClass.xVal()

So far I have this:

priority_queue<MyClass, vector<MyClass>, greater<MyClass>> queue;

Of course, it doesn't do what I expect.I complies but uses some random ordering for my objects. Would appreciate it if someone can point out what I am doing wrong.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
205 views
Welcome To Ask or Share your Answers For Others

1 Answer

The CPP Reference link to Priority Queue provides that a priority queue can be defined as:

template<
    class T,
    class Container = std::vector<T>,
    class Compare = std::less<typename Container::value_type>
> class priority_queue;

Here, T=MyClass and Container=std::vector<MyClass>. The only thing that remains is Compare which as has been mentioned above can be implemented using either Lambdas or Functors. I'll show both:

Let's say the class is defined as shown below with xVal() method's return value as the sort key:

struct MyClass{
    int count;
    int key;
    int xVal() { return count; };
};

Using Lambdas

//  Lambda skeleton: [capture preferences](arguments){ body }
auto cmp = [](MyClass left, MyClass right) {return left.xVal() > right.xVal();};
std::priority_queue<MyClass, std::vector<MyClass>, decltype(cmp)> queue(cmp);

Using a Functor

struct CmpFunctor{
    bool operator()(MyClass left, MyClass right) const {
        return left.xVal() > right.xVal();
    }
};
auto cmp = CmpFunctor()
std::priority_queue<MyClass, std::vector<MyClass>, decltype(cmp)> queue(cmp);

Here is a link showing the running code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...