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.
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.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_queuetakes 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.