The Wayback Machine - https://web.archive.org/web/20240613215520/https://www.geeksforgeeks.org/functors-in-cpp/
Open In App

Functors in C++

Last Updated : 27 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Please note that the title is Functors (Not Functions)!!

Consider a function that takes only one argument. However, while calling this function we have a lot more information that we would like to pass to this function, but we cannot as it accepts only one parameter. What can be done?

One obvious answer might be global variables. However, good coding practices do not advocate the use of global variables and say they must be used only when there is no other alternative.

Functors are objects that can be treated as though they are a function or function pointer. Functors are most commonly used along with STLs in a scenario like following:

Below program uses transform() in STL to add 1 to all elements of arr[]. 

CPP




// A C++ program uses transform() in STL to add
// 1 to all elements of arr[]
#include <bits/stdc++.h>
using namespace std;
  
int increment(int x) {  return (x+1); }
  
int main()
{
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr)/sizeof(arr[0]);
  
    // Apply increment to all elements of
    // arr[] and store the modified elements
    // back in arr[]
    transform(arr, arr+n, arr, increment);
  
    for (int i=0; i<n; i++)
        cout << arr[i] <<" ";
  
    return 0;
}


Output:

2 3 4 5 6

Time Complexity: O(n)

Space Complexity: O(n) where n is the size of the array.

This code snippet adds only one value to the contents of the arr[]. Now suppose, that we want to add 5 to contents of arr[].

See what’s happening? As transform requires a unary function(a function taking only one argument) for an array, we cannot pass a number to increment(). And this would, in effect, make us write several different functions to add each number. What a mess. This is where functors come into use.

A functor (or function object) is a C++ class that acts like a function. Functors are called using the same old function call syntax. To create a functor, we create a object that overloads the operator().

The line,
MyFunctor(10);

Is same as
MyFunctor.operator()(10);

Let’s delve deeper and understand how this can actually be used in conjunction with STLs. 

CPP




// C++ program to demonstrate working of
// functors.
#include <bits/stdc++.h>
using namespace std;
 
// A Functor
class increment
{
private:
    int num;
public:
    increment(int n) : num(n) {  }
 
    // This operator overloading enables calling
    // operator function () on objects of increment
    int operator () (int arr_num) const {
        return num + arr_num;
    }
};
 
// Driver code
int main()
{
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr)/sizeof(arr[0]);
    int to_add = 5;
 
    transform(arr, arr+n, arr, increment(to_add));
 
    for (int i=0; i<n; i++)
        cout << arr[i] << " ";
}


Output:

6 7 8 9 10

Time Complexity: O(n)

Space Complexity: O(n) where n is the size of the array.

Thus, here, Increment is a functor, a c++ class that acts as a function.

The line,
transform(arr, arr+n, arr, increment(to_add));

is the same as writing below two lines,
// Creating object of increment
increment obj(to_add); 

// Calling () on object
transform(arr, arr+n, arr, obj); 

Thus, an object a is created that overloads the operator(). Hence, functors can be used effectively in conjunction with C++ STLs.



Previous Article
Next Article

Similar Reads

C++ - Difference Between Functors and Functions
In C++, we have multiple options to operate over the data like in the case where we can use functions and functors. Although both seem to be similar in a few ways but have multiple differences between them. Let's check the differences between functions and functors in C++. What are functions? Functions are pieces of code that can be called from any
3 min read
How to Use Binder and Bind2nd Functors in C++ STL?
Functors in C++ (also known as function objects) are objects that can be treated as if they are functions. They can be called a function, but they can also have an internal state and can be passed around like any other object. This can be useful when you want to pass a function as an argument to another function, but you want the function to have s
4 min read
Sort an array according to absolute difference with given value using Functors
Given an array of n distinct elements and a number x, arrange array elements according to the absolute difference with x, i. e., the element having a minimum difference comes first and so on. Note: If two or more elements are at equal distance arrange them in same sequence as in the given array. Examples: Input : x = 7, arr[] = {10, 5, 3, 9, 2} Out
6 min read
When to Prefer Lambda Expressions over Functors in C++?
In C++, lambda expressions and functors (function objects) both are used for defining anonymous or named functions in C++. In this article, we will learn when to use a lambda expression instead of a functor in C++. When to Prefer Lambda instead of Functors?Prefer to use a lambda expression instead of a functor in the following cases: 1. Short-lived
4 min read
Article Tags :
Practice Tags :