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/