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

时间:2014-07-24 02:02:03

标签: 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&amp ;. 我以为会是

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构造函数范例的明确定义。

另外,为什么有时会超载&#34;&lt;&#34;作为比较器。有时超载&#34;()&#34;比较器? 感谢

1 个答案:

答案 0 :(得分:3)

默认比较为std::less< Star >,会调用您已定义的operator <

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

priority_queue<Star> max_heap;

  

另外,为什么有时会超载&#34;&lt;&#34;作为比较器。有时超载&#34;()&#34;作为比较器?

比较器始终是Callable对象,即函数或类函数对象(functor)。使用带括号的函数调用表示法传递要比较的内容。 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 <的电话就是这样。