2013-06-22 61 views
0

我已经看过移到该thread其中谈到使用这种方法用于比较:C++ STL priority_queue与结构Clearification

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()的含义。什么是运算符重载?

另外,从cplusplus on priority_queue,我不太了解以下内容,主要是第二个参数。

template < class T, class Container = vector<T>, 
     class Compare = less<typename Container::value_type> > class priority_queue; 

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

此外,有什么区别,哪种方法是首选?

回答

1

我不能确定重载操作符operator()是什么意思。 什么是运算符重载?

我们在这里是函数调用运算符(see SO question)的过载,这意味着客户端代码可以“享受”的CompareTime类实例的比较功能:

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

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

cplusplus参考总结相当好,模板参数:

  • 0精氨酸 - 类型的队列内的对象。
  • 1 ARG - 为对队列中的底层的容器/数据结构中,通过 默认其在std矢量
  • 2 ARG - 对优先级队列操作依赖于一些优先 比较,即,在队列中的项之前应该是” '另一项(也可参见Wikipedia,所以这个arg接受比较对象(函子),它意味着重载()运算符的纯类的实例,默认值是std less函子,它只是'<'语义之上的包装器(布尔2值函数对象)

//模板结构少

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