带有struct Clearification的C ++ STL priority_queue

时间:2013-06-22 18:16:41

标签: syntax struct priority-queue

我已经查看了这个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;

换句话说,我不理解第二种方法及其调用约定。

另外,有什么区别,哪种方法更受欢迎?

1 个答案:

答案 0 :(得分:1)

  

我不确定重载运算符operator()的含义。   什么是运算符重载?

我们这里有一个函数调用操作符(see SO question)的重载,这意味着客户端代码可以将CompareTime类实例“视为”比较函数:

CompareTime ct;
if ( ct(t1, t2) ) 
{
...
} 
  

我不太了解以下内容,主要是第二个参数。

cplusplus参考总结了模板参数:

  • 0 arg - 队列中对象的类型。
  • 1 arg - 队列的基础容器/数据结构 默认为std向量
  • 2 arg - 优先级队列上的操作依赖于某些优先级 比较,即队列中的哪个项目应该在“其他项目之前”(另请参阅Wikipedia),因此这个arg接受比较对象(仿函数),它表示普通类的实例,它重载了()运算符,默认情况下是std 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); 
    } 
};