
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Functors in C++
The functors are the function objects in C++. The functor allows an instance object of some class to be called as if it were an ordinary function. Let us consider a function that takes one argument. We can use this function as function object to do some task on a set of data.
The Functors are widely used in STL algorithms like transform(), sort(), etc.
Functor vs Regular Function: Need of Functor?
Imagine we have a function that takes only one argument, like this:
int increment(int x) { return x + 1; }
Now, what if we want to add different numbers, not just 1. For example, add 5 instead of 1. Then we have to write a new function every time.
int addFive(int x) { return x + 5; } int addTen(int x) { return x + 10; }
This will be tough to write and manage the functions. So, when we need to pass extra data (like "how much to add") into the function. Functors helps to resolve and work with this in a good way.
Let us go through an examples for better understanding with and without using Functors.
Using a Functor
Using a Functor, we can customize the value to add by storing it inside the object which will overcome the problem that we were facing in traditional functions (as discussed above).
Example
In this example, we define a functor class that adds a fixed number to any given value. In the main() function, we use the transform() function to add 5 to each element of the array by passing an object of the functor:
#include<bits/stdc++.h> using namespace std; // Define a class with operator() class increment { int num; public: increment(int n) : num(n) {} int operator() (int x) const { return x + num; } }; int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); int to_add = 5; // Pass functor to transform transform(arr, arr + n, arr, increment(to_add)); for (int i = 0; i < n; i++) cout<<arr[i]<<" "; }
Following is the output to the above program:
6 7 8 9 10