我已经查看了这个thread,其中讨论了使用此方法进行比较:
struct thing
{
int a;
char b;
bool operator<(const thing &o) const
{
return a < o.a;
}
};
priority_queue<thing> pq;
另一方面,其他使用方法如下:
struct Time {
int h;
int m;
int s;
};
class CompareTime {
public:
bool operator()(Time& t1, Time& t2) // Returns true if t1 is earlier than t2
{
if (t1.h < t2.h) return true;
if (t1.h == t2.h && t1.m < t2.m) return true;
if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
return false;
}
}
priority_queue<Time, vector<Time>, CompareTime> pq;
虽然我用第一种方法来自我逻辑,但我不会放弃理解第二种方法。主要是因为语法。我不确定重载运算符operator()
的含义。什么是运算符重载?
另外,从priority_queue上的cplusplus开始,我不太了解以下内容,主要是第二个参数。
template < class T, class Container = vector<T>,
class Compare = less<typename Container::value_type> > class priority_queue;
换句话说,我不理解第二种方法及其调用约定。
另外,有什么区别,哪种方法更受欢迎?
答案 0 :(得分:1)
我不确定重载运算符operator()的含义。 什么是运算符重载?
我们这里有一个函数调用操作符(see SO question)的重载,这意味着客户端代码可以将CompareTime
类实例“视为”比较函数:
CompareTime ct;
if ( ct(t1, t2) )
{
...
}
我不太了解以下内容,主要是第二个参数。
cplusplus参考总结了模板参数:
less
仿函数,它只是'&lt;'语义(布尔值为2的函数对象)上面的包装器。// TEMPLATE STRUCT less
template<class _Ty>
struct less : public binary_function<_Ty, _Ty, bool>
{
// functor for operator<
bool operator()(const _Ty& _Left, const _Ty& _Right) const
{
// apply operator< to operands
return (_Left < _Right);
}
};