-1

The below piece of code is very common to implement Min-Heap :

struct comparator
{
    bool operator() ( int i, int j)
    { return j < i; }
};

priority_queue<int, std::vector<int>, comparator> minHeap;

How Functors work? What purpose they solve in C++? I could see Functors are more often used to Overload comparison. Are they just used to make Operator Overloading easy?

When to create Functors? How to create our own functor?

Prasath Govind
  • 720
  • 2
  • 10
  • 30

2 Answers2

2

The comparator struct is an example of something usually called a 'functor' in C++. A functor is a 'callable object' - that is a regular object that implements operator(), the function call operator. When used like this in an STL container, you are passing the type of the functor rather than an instance of it as a template argument. The container will create instances as necessary in order to actually call operator() on them.

If you are familiar with lambdas in C++, they are really just syntactic sugar for functors. A lambda definition creates an anonymous type which you can think of as a compiler-generated functor type with an operator() corresponding to the lambda function.

Functors (or lambdas) are the standard way in C++ to pass functions to types or other functions. This is useful in many situations, the example allows you to customize the sorting criteria for the priority_queue. The STL uses functors all over the place in containers and the algorithms library as a way to parameterize types and functions on a user supplied function.

mattnewport
  • 13,728
  • 2
  • 35
  • 39
1

comparator is functor type used internally to sort container.

cppreference

By default STL uses builtin comparator std::less that is doing i < j. In your example custom comparator is used to sort container in reversed order. Your example can be rewritten as:

priority_queue<int, std::vector<int>, std::greater> minHeap;
Elohim Meth
  • 1,777
  • 9
  • 13