what are functors in c++ and its uses explain with example?

functors are called function objects. Basically functors are classes or structs which overide operator ().  Overloading operator() enables us to create objects which “look like” a function. Let us see below example. The class add which is overloading operator().

#include<iostream>
using namespace std;

class add {
public:
	int operator()(int a, int b) {
		return a + b;
	}
};

int main() {
	add obj;
	cout << obj(4, 3) << endl;
	return 0;
}

In the above example object of class add behaves like a function.

  • A simple use case of using functor in templates.

Let us assume we have a vector<int> vec = { 1,3,5,8,7,9}. now we need to count how many integers in  vec are greater than 5 using count_if algorithm.

As we know  std::algorithm::count_if() function
takes three parameters 


    first − Input iterators to the initial positions of the stl container.

    last − Input iterators to the final positions of the stl container.

    pred − predicate (function )/functor which takes an argument and returns bool.

Let us see below example using functor in count_if in c++

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

// functor
struct isGreater {
	bool operator ()(int n) {
		return (n > 5);
	}
};

int main(void) {

	vector<int> v = { 1, 3, 5, 8, 7, 9 };
	int c;

	// using functor
	c = count_if(v.begin(), v.end(), isGreater());
	cout << "There are " << c << " integers are greater that 5." << endl;

	return 0;
}

what are advantages of using functors in c++

  • Functors may have state while function does not.
  • Most of the compilers often transform functors as inlined.
  • Functors can be used to implement callbacks.

Ref:

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



Related Contents to follow