【问题标题】:Custom comparer for priority_queue object in a class类中priority_queue对象的自定义比较器
【发布时间】:2021-08-18 17:57:45
【问题描述】:

我有一个结构类似于以下骨架代码的类。

class custom
{
private:
  struct info
  {
    // define some stuff
  };
  std::priority_queue<info, vector<info>, custom_comparer_t> pq;
}

我想知道在这种情况下是否应该定义custom_comparer_t 的标准?最好使用 lambda 函数、仿函数,还是在 info 中重载 &lt;&gt; 运算符?

【问题讨论】:

    标签: c++ lambda operator-overloading priority-queue functor


    【解决方案1】:

    std::priority_queue模板参数根据cppreference

    template<
        class T,
        class Container = std::vector<T>,
        class Compare = std::less<typename Container::value_type>
    > class priority_queue;
    

    std::priority_queueCompare模板参数必须满足Compare概念要求。而std::priority_queue 不能使用T::operator()() 因为:

    1. 它会破坏其他 STL &lt;algorithm&gt; 函数。
    2. T 可以是 POD 类型或用户定义的类型,结果将是 std::priority_queue 的复杂实现。

    当然,你可以为Compare 使用函子:

    class custom {
     private:
      struct info {
        // define some stuff
        bool operator()(info const&, info const&) const {
          return false;
        }
      };
    
     private:
      using custom_comparer_t = info;
      std::priority_queue<info, std::vector<info>, custom_comparer_t> pq;
    };
    

    【讨论】:

    • 我明白了。我通常将仿函数和 lambda 用于自定义类。在这种情况下,这两者中的任何一个会比另一个更好吗?
    • @roulette01,我编辑了答案,请再次查看。
    • 你能补充一下为什么函子在这里比 lambda 函数更有利吗?
    • @roulette01,对不起。我不知道设计的确切答案。但我猜想这是因为在 C++20 之前我们无法将 lambda 作为模板参数传递。
    • using custom_comparer_t = info; 的目的是什么?除了作为存储在 PQ 中的对象类型之外,您还要将其用作优先级队列中的自定义比较器,是否更明确?
    猜你喜欢
    • 1970-01-01
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    • 2013-04-13
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    相关资源
    最近更新 更多