问题描述
假设我有一个名为 MyClass
的类,每个 MyClass 对象都有一个名为 xVal
的方法.我想要的是按 MyClass.xVal()
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.
谢谢.
推荐答案
CPP 参考链接到优先队列规定优先队列可以定义为:
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;
这里,T=MyClass
和 Container=std::vector
.唯一剩下的是 Compare
,正如上面提到的,可以使用 Lambdas 或 Functors 来实现.我会同时展示:
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:
假设类定义如下,xVal()
方法的返回值作为排序键:
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; };
};
使用 Lambda
// 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);
使用函子
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.
这篇关于C++优先队列按对象的特定方法升序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!