0

Firstly, I find that priority_queue<int> will give higher priority to bigger integer. While if we use priority_queue<int, vector<int>, greater> then it do it in an inverse. Why?

Also, it seems that the comparator we put in the priority queue is not a function pointer. Instead it was defined as:

struct cmp{
    bool operator() (const int& lhs, const int&rhs) const
    {
        ...
    }
}

I heard this is a very useful property of C++; could anyone explains this type of code to me?

Shoe
  • 74,840
  • 36
  • 166
  • 272
user3341953
  • 309
  • 1
  • 5
  • 14
  • possible duplicate of [C++ Functors - and their uses](http://stackoverflow.com/questions/356950/c-functors-and-their-uses) – Shoe Mar 07 '14 at 01:19

3 Answers3

2

It's a functor. It's basically a class/object that acts like a function by overloading operator(). For example in your code you could do:

cmp func;
func(1, 2);
// ^ calls operator()

You can read more about them here.

Community
  • 1
  • 1
Shoe
  • 74,840
  • 36
  • 166
  • 272
0

The benefit of this kind of code is that if the type is templated you can put in a function pointer OR a class like the above (a functor). In either case they both work, the first is simpler while the second can have data given to it. Lambdas in c++11 makes them a little redundant though.

Cramer
  • 1,785
  • 1
  • 12
  • 20
0

Functors are often used to maintain state across an algorithm. Consider the following search function:

struct Foo { int x };
std::vector<Foo> fooList; // Imagine this is populated.

struct FindFunc
{
    FindFunc(int toFind) : val(toFind) {}
    bool operator()(const Foo& el) { return el.x == val; }
    int val;
};

// Seach the list of Foo objects for one where member x is 42
std::find_if(fooList.begin(), fooList.end(), FindFunc(42));
Aesthete
  • 18,622
  • 6
  • 36
  • 45