C++ 基于条件c+重新排序优先级_队列+;

C++ 基于条件c+重新排序优先级_队列+;,c++,pointers,struct,priority-queue,C++,Pointers,Struct,Priority Queue,我正在尝试根据用户需求重新排列优先级队列 这是数据结构: struct Person{ 智力年龄; 浮动高度; }; 我单独使用这个结构以递减的方式对其重新排序 struct CompareHeight { bool operator()(Person const& p1, Person const& p2) { // return "true" if "p1" is ordered // before "p2", fo

我正在尝试根据用户需求重新排列优先级队列

这是数据结构:

struct Person{
智力年龄;
浮动高度;
};
我单独使用这个结构以递减的方式对其重新排序

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; 
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; 
我单独使用这个结构,以递增的方式对它进行重新排序

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; 
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; 
struct CompareHeightInv{
布尔运算符()(人员常量和p1,人员常量和p2)
{ 
//如果订购了“p1”,则返回“true”
//在“p2”之前,例如:
返回p1.height
我把每个人都称为:

priority\u队列公司;
优先级队列dec;
我的问题是:有没有这样的方式

class Foo {
private:
     ...
     priority_queue<Person, vector<Person>, something> myQueue; 
     ...
public:
     Foo (bool flag) {
          if (flag)
             myQueue is increasing
          else
             myQueue is deacreasing
     }

}
class-Foo{
私人:
...
优先级队列;
...
公众:
富(布尔旗){
国际单项体育联合会(旗)
我的队列在增加
其他的
我的队列正在减少
}
}

一种可能也是最简单的方法是将附加标志传递给比较器,并且只有一个:

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;
};
struct CompareHeight{
比较权重(bool-asc):升序(asc){}
布尔运算符()(人员常量和p1,人员常量和p2)
{ 
如果(上升)返回p1.heightp2.height;
} 
布尔上升;
};
然后使用它:

CompareHeight comparator( str == "increasing" );
priority_queue<Person, vector<Person>, CompareHeight> queue( comparator );
CompareHeight比较器(str==“递增”);
优先级队列(比较器);
或者只有一行:

priority_queue<Person, vector<Person>, CompareHeight> queue( CompareHeight( str == "increasing" ) );
priority_队列(比较高(str==“增加”);

否则,您可以使用
std::function
作为类型并传递特定类型,或者使用继承并使两个比较器都从公共基派生。这两种方法都非常冗长。

编辑你的问题,而不是评论如果
str
是constexpr,那么你可以使用
如果constexpr
。如果没有,那么您将需要泛化代码,使其不受优先级队列的影响。如果
str
是constexpr,您也可以使用
std::conditional\u t