c++ - 运算符重载 'operator()'

标签 c++ operators overloading priority-queue dijkstra

我正在实现 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;
}

更具体地说,“bool operator() (const int& lhs, const int&rhs) const”让我感到困惑。其余的我都很好。我认为它重载了一个运算符,但“operator()”对我来说毫无意义。任何帮助将不胜感激。

最佳答案

本质上,operator()“只是”另一个可以重载的运算符,所以您所知道的关于运算符重载的一切仍然适用——它很有用,因为它可以应用于具有相同语法的对象你可以用来调用一个函数,例如

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

也就是说,除此之外,还有很多关于仿函数等的内容 - 您可能想在 Google 上搜索仿函数/函数对象以获取更多信息。这是一个链接:

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

在上面的代码中,priority_queue 采用了一个比较仿函数,用于对放入队列的内容进行排序。第一个队列(fifth)使用正常排序;第二个队列(第六个)使用倒序。

关于c++ - 运算符重载 'operator()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13437029/

相关文章:

java - 具有不同签名但相同主体的功能

c++ - 带有 LANG=en_US.UTF-8 的 MacOS 10.6 上的 std::locale 损坏

c++ - 如何在 Windows 上使用 Eclipse 交叉编译树莓派

c++ - 在 C++ 中正确重载 +

java - 在设置某些属性时,竖线 (|) 运算符如何在 Android 中工作?

javascript - 何时在 JavaScript 中使用双非 (!!) 运算符

c++ - 模数代码简化

c++ - 在 C++ 类继承中使用函数

c++ - C++中运算符重载的语法是什么?

c++ - 为什么运算符 << 不明确?