问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/53109569/c-priority-queue-in-ascending-order-by-specific-method-for-objects