Search code examples
c++priority-queuemin-heapmax-heap

c++ priority_queue initialization. Why can we ignore const Compare&


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;

Look at last line. This is priority_queue max_heap's initialization. Why it ignore the c++ const Compare&. I thought it would be

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

It looks different as below one, which I understand.

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

I read this page: http://www.cplusplus.com/reference/queue/priority_queue/priority_queue/

cannot get the definitive definition of priority_queue constructor paradigm.

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


Solution

  • The default comparison is std::less< Star > which will call the operator < you have defined.

    Template type parameters can have deault arguments, just like function parameters. It's the same with the default container type, which is std::vector< Star >. Actually you can write the declaration simply as

    priority_queue<Star> max_heap;
    

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

    The comparator is always a Callable object, that is, a function or function-like object (functor). The things to be compared are passed using function-call notation with parentheses. std::less is the adaptor which makes a given bool operator< (T, T) overload accessible as the member operator() of a functor.

    For example, here is how std::less may be implemented:

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

    std::less is actually an object type, and such an object is actually stored inside the priority_queue. Its operator() is what makes the comparison. The call to your operator < happens this way.