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 构造函数范式的明确定义。
另外,为什么有时它会重载“<”作为比较器。有时重载“()”作为比较器? 谢谢