【问题标题】:reordering priority_queue based on condition c++根据条件c ++重新排序priority_queue
【发布时间】:2020-05-13 13:03:48
【问题描述】:

我正在尝试根据用户需求重新排序 priority_queue。

这是数据结构:

struct Person { 

    int age; 

    float height; 
};

我单独使用这个结构来以递减的方式重新排序

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; 

我每个人都通过以下方式称呼每个人:

priority_queue<Person, vector<Person>, CompareHeightInv> inc; 

priority_queue<Person, vector<Person>, CompareHeight > dec; 

我的问题是:有没有这样的方法

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

}

【问题讨论】:

  • 编辑你的问题,而不是评论
  • 如果str 是constexpr,那么你可以使用if constexpr。如果没有,那么您将需要生成您的代码,使其与优先级队列无关。如果str是constexpr,也可以使用std::conditional_t&lt;str == "increasing", CompareHeightInv, CompareHeight&gt;

标签: c++ pointers struct priority-queue


【解决方案1】:

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

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;
};

然后使用它:

CompareHeight comparator( str == "increasing" );
priority_queue<Person, vector<Person>, CompareHeight> queue( comparator );

或者只有一行:

priority_queue<Person, vector<Person>, CompareHeight> queue( CompareHeight( str == "increasing" ) );

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

【讨论】:

    猜你喜欢
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 2018-07-29
    相关资源
    最近更新 更多