2012-11-18 113 views
0

我正在实现Dijkstra的算法,我想使用STL的'priority_queue'来加速编码过程,但是我经常遇到这种情况,因为我试图用C++进行编码,对语言的理解正在减慢我的速度。我发现这个例子在http://www.cplusplus.com/reference/stl/priority_queue/priority_queue/,但不明白下面是这样做的:运算符重载运算符()'

// constructing priority queues 
#include <iostream> 
#include <queue> 
using namespace std; 

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

    priority_queue<int> first; 
    priority_queue<int> second (myints,myints+4); 
    priority_queue< int, vector<int>, greater<int> > third (myints,myints+4); 

    // using mycomparison: 
    priority_queue< int, vector<int>, mycomparison > fourth; 

    typedef priority_queue<int,vector<int>,mycomparison> mypq_type; 
    mypq_type fifth (mycomparison()); 
    mypq_type sixth (mycomparison(true)); 

    return 0; 
} 

更具体地讲,“布尔运算符()(const int的& LHS,const int的&右)常量”是什么绊倒我。剩下的我很好。我认为它重载了一个操作符,但'operator()'对我来说没有意义。任何帮助,将不胜感激。

+0

现在回想起来,这是一个坏主意后,我发现因为我是有只是这个问题的代码全部正在超载的运营商。 – Daeden

回答

2

实质上,operator()是“正义”的另一个可以重载的运算符,因此,有关运算符重载的所有知识仍然适用 - 这很有用,因为它可以应用于具有与用于调用函数相同语法的对象,例如

MyClass f; 
f(); // i.e. f.operator()(); 

这就是说,有很多可能有关函子等超出了说 - 你可能想要做一个谷歌搜索仿函数/函数对象以获取更多信息。这里有一个链接:

http://en.wikipedia.org/wiki/Function_object

在上面的代码,priority_queue需要它使用命令你把队列的东西进行比较仿函数。第一个队列(fifth)使用正常排序;第二个队列(sixth)使用反向排序。

+0

提及仿函数+1!将您的链接添加到我的阅读列表。 – Daeden

0
bool operator() (const int &, const int &); 

这是一个函数,operator()的重载,它接受两个整数并返回一个布尔值。 const表示该值不能更改。它代表常数

1

这是函数调用操作,您可以使用它像这样:

mycomparison mycomp; //defines an object 
mycomp(1,2); // invokes operator()(int,int) 
+0

我可能在解释我的问题时做了一件糟糕的工作,但是显示如何调用操作员真的很有帮助! – Daeden