【问题标题】:C++ STL priority_queue with struct Clearification具有结构清除的 C++ STL priority_queue
【发布时间】:2013-06-22 18:16:41
【问题描述】:

我查看了这个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() 的含义。那个运算符重载是什么?

还有,从cplusplus上priority_queue,下面的我不太明白,主要是第二个参数。

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

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

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

【问题讨论】:

    标签: syntax struct priority-queue


    【解决方案1】:

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

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

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

    下面的不太明白,主要是第二个参数。

    cplusplus参考总结的很好,模板参数:

    • 0 arg - 队列中对象的类型。
    • 1 arg - 队列的底层容器/数据结构,由 默认是标准向量
    • 2 arg - 对优先级队列的操作依赖于某些优先级 比较,即队列中的哪个项目应该在其他项目之前(另请参见Wikipedia,因此此参数接受具有比较对象(函子),这意味着普通类的实例重载 () 运算符,默认为std 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); 
        } 
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-03
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 2011-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多