[英]reordering priority_queue based on condition c++
I am trying to reorder priority_queue based on user demand.我正在尝试根据用户需求重新排序 priority_queue。
This is the data struct:这是数据结构:
struct Person {
int age;
float height;
};
I used this struct separately to reorder it in a decreasing way我分别使用这个结构以递减的方式重新排序
struct CompareHeight {
bool operator()(Person const& p1, Person const& p2)
{
// return "true" if "p1" is ordered
// before "p2", for example:
return p1.height > p2.height;
}
} HI;
and I used this struct separately to reorder it in an increasing way我分别使用这个结构来以越来越多的方式重新排序
struct CompareHeightInv {
bool operator()(Person const& p1, Person const& p2)
{
// return "true" if "p1" is ordered
// before "p2", for example:
return p1.height < p2.height;
}
} HD;
and I call each speratlly by:我通过以下方式给每个人打电话:
priority_queue<Person, vector<Person>, CompareHeightInv> inc;
priority_queue<Person, vector<Person>, CompareHeight > dec;
My question is: is there a way that like this我的问题是:有没有这样的方法
class Foo {
private:
...
priority_queue<Person, vector<Person>, something> myQueue;
...
public:
Foo (bool flag) {
if (flag)
myQueue is increasing
else
myQueue is deacreasing
}
}
One of the way and probably simplest, is to pass additional flag to your comparator and have only one:一种可能最简单的方法是将附加标志传递给您的比较器并且只有一个:
struct CompareHeight {
CompareHeight( bool asc ) : ascending( asc ) {}
bool operator()(Person const& p1, Person const& p2)
{
if(ascending) return p1.height < p2.height;
return p1.height > p2.height;
}
bool ascending;
};
then use it:然后使用它:
CompareHeight comparator( str == "increasing" );
priority_queue<Person, vector<Person>, CompareHeight> queue( comparator );
or just one line:或者只有一行:
priority_queue<Person, vector<Person>, CompareHeight> queue( CompareHeight( str == "increasing" ) );
Otherwise you can use std::function
as a type and pass specific type or use inheritance and have both comparators to derive from common base.否则,您可以使用
std::function
作为类型并传递特定类型或使用 inheritance 并让两个比较器从公共基础派生。 Both ways are significantly more verbose.两种方式都更加冗长。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.