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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…