c++ priority_queue 初始化。为什么我们可以忽略 const Compare&

标签 c++ priority-queue min-heap max-heap

class Star {
 public:
  // The distance between this star to the Earth.
  double distance() const { return sqrt(x_ * x_ + y_ * y_ + z_ * z_); }

  bool operator<(const Star& s) const { return distance() < s.distance(); }

  int ID_;
  double x_, y_, z_;
};



priority_queue<Star, vector<Star>> max_heap;

看最后一行。这是priority_queue max_heap的初始化。为什么它忽略了 c++ const Compare&。 我以为会是

priority_queue<Star, vector<Star>, Star> max_heap;

它看起来和下面的不一样,我明白了。

class mycomparison
{
  bool reverse;
public:
  mycomparison(const bool& revparam=false)
    {reverse=revparam;}
  bool operator() (const int& lhs, const int&rhs) const
  {
    if (reverse) return (lhs>rhs);
    else return (lhs<rhs);
  }
};

int main ()
{
  int myints[]= {10,60,50,20};

  std::priority_queue<int> first;
  std::priority_queue<int> second (myints,myints+4);
  std::priority_queue<int, std::vector<int>, std::greater<int> >
                            third (myints,myints+4);
  // using mycomparison:
  typedef std::priority_queue<int,std::vector<int>,mycomparison> mypq_type;

  mypq_type fourth;                       // less-than comparison
  mypq_type fifth (mycomparison(true));   // greater-than comparison

  return 0;
}

我读了这个页面: http://www.cplusplus.com/reference/queue/priority_queue/priority_queue/

无法获得 priority_queue 构造函数范式的明确定义。

另外,为什么有时它会重载“<”作为比较器。有时重载“()”作为比较器? 谢谢

最佳答案

默认比较是std::less< Star >这将调用 operator <你已经定义了。

模板类型参数可以有默认参数,就像函数参数一样。它与默认容器类型相同,即 std::vector< Star > .实际上你可以简单地把声明写成

priority_queue<Star> max_heap;

Also, Why sometimes it overloads "<" as comparator. Sometimes overloads "()" as comparator?

比较器始终是 Callable 对象,即函数或类函数对象(仿函数)。要比较的事物使用带括号的函数调用符号传递。 std::less是使给定 bool operator< (T, T) 的适配器重载可作为成员访问 operator()一个仿函数。

例如,这里是std::less可能实现:

template< typename T >
struct less {
    bool operator () ( T const & lhs, T const & rhs ) const
        { return lhs < rhs; } // Calls Star::operator < ()
};

std::less实际上是一个对象类型,而这样一个对象实际上是存储在priority_queue里面的.它的operator()是什么使比较。打给您的 operator <以这种方式发生。

关于c++ priority_queue 初始化。为什么我们可以忽略 const Compare&,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24923958/

相关文章:

c++ - 为什么将类作为参数传递需要默认构造函数?

java - 使用javapriorityQueue删除方法

c++ - std::priority_queue 中的比较器

python - 基于数组的 MinHeap

java - 使用数组 : Insert and Remove Min (with duplicates) 实现最小堆

.net - C++ 到 .Net

c++ - const 限定符从纯虚函数中消失

c++ - 如果我删除指向节点的指针数组,节点本身会被删除吗?

java - PriorityQueue 是否保持自然顺序?

algorithm - 如何更新堆中的元素? (优先队列)