0
votes

I am implementing Dijkstra's algorithm and I would like to use STL's 'priority_queue' to speed up the coding process, but as so often is the case with my attempts at coding in C++, my lack of understanding of the language is slowing me down. I found this example at http://www.cplusplus.com/reference/stl/priority_queue/priority_queue/, but do not understand what the following is doing:

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

To be more specific, 'bool operator() (const int& lhs, const int&rhs) const' is what is tripping me up. The rest I am fine with. I think its overloading an operator, but 'operator()' makes no sense to me. Any help would be appreciated.

3
In retrospect, it was a bad idea to post the entirety of the code I found as the issue I was having was only with the operator that was being overloaded. - Daeden

3 Answers

2
votes

Essentially, operator() is "just" another operator that can be overloaded, so everything you know about operator overloading still applies - it's useful because it can be applied to an object with the same syntax that you might use to call a function, e.g.

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

That said, there's a lot that could be said about functors etc. beyond that - you might want to do a Google search for functors / function objects for more information. Here's one link:

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

In the above code, priority_queue takes a comparison functor that it uses to order the things you put in the queue. The first queue (fifth) uses normal ordering; the second queue (sixth) uses reverse ordering.

1
votes

That is the function call operator and you can use it like this:

mycomparison mycomp;  //defines an object
mycomp(1,2);  // invokes operator()(int,int)
0
votes
bool operator () ( const int &, const int & );

This is a function, an overload of operator(), that takes two integers and returns a boolean. const means that the value cannot be changed. It stands for constant.