Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

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

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...