×

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It is true that it surely has a connection with function. Often it is called a function pointer. Now, we have to understand the context of this functor. Suppose, in programming, you face a situation where you need to add the count of parameters in a function. But this task is restricted. You can not increase the parameters. So, now you can think of another function. Maybe you can get the idea of using a global variable instead of using parameters. So, these methods can do your job, but they are not optimised. Here come functors. By using functors, we can easily pass more parameters to a function. In this article, we will discuss functors in detail. Keep reading to know more about this thing.

What is a functor?

The term "functor" refers to an object that can be used to refer to a function or function pointer. The most frequent application of functors is in conjunction with STLs. Any object that may be used with () in the same way as a function is a functor. The () operator (function call operator) is overloaded for class objects that are regular functions, pointers to functions, and class objects for which the function operator()() is specified. When a regular function fails, we can occasionally utilise a function object. The STL offers a number of really useful function objects and frequently uses them. Another illustration of the efficacy of generic programming and the idea of pure abstraction is the concept of function objects. Anything that behaves like a function is a function, we could argue.

What is the scenario for using functors?

We have discussed one case at the beginning of the article. Functors are mainly used when we need to change the parameter, but it is restricted. Mainly in STL, it is used very much. Suppose you are writing one program where you have to use the sorting algorithm provided by the STL. Now it will only give you the output in ascending order. Suppose you want to implement this sorting with some extra conditions. Here you can use functor. See the below given example where we have used the transform operator to transform the array by using one function.

Example:

#include <bits/stdC++.h>
using namespace std;


int fun( int x ) { 
	x = x + 1;
return x;
}


int main()
{
	int arr[] = { 12, 14, 2, 3, 8, 10, 7, 6, 20, 30, 15};
	int n = sizeof(arr)/sizeof(arr[0]);
	transform(arr, arr+n, arr, fun);


	for (int i=0; i<n; i++)
		cout << arr[i] <<" ";


	return 0;
}

Output:

Functors in C++

Code Explanation:

As you can see from the previous code, the program will increase our array by inserting value one into each value of the array. We have used the transform function from STL to do this. We have declared one function, named fun, to increment the value by 1. In the function, we have given only one parameter, which is the value from the indexed array. Now suppose one user is demanding that he wants to change the value of the user randomly. He wants to change the values of the array by incrementing it randomly. Now we have no choice left but to add one more parameter in the function. But wait, it is not that much easy because the transform function only takes the function with one parameter as input.

So, here we face the problem. We cannot provide a number to fun because transform requires a unary function (a function with only one argument) for an array (). And as a result, we would have to construct many functions to add each integer. Functors are useful in situations like these. A C++ class that simulates a function is known as a functor (or function object). The same function call syntax is used to call a functor. We develop an object that overloads the operator to produce a functor (). You can see the implementation below the given code.

Example:

#include <bits/stdC++.h>
using namespace std;
class fun
{
private:
	int num;
public:
	fun(int n) : num(n) { }
	int operator () (int arr_num) const {
		return num + arr_num;
	}
};
int main()
{
	int arr[] = { 12, 14, 2, 3, 8, 10, 7, 6, 20, 30, 15};
	int n = sizeof(arr)/sizeof(arr[0]);
	int add = 5;


	transform( arr, arr+n, arr, fun( add ) );


	for (int i=0; i<n; i++)
		cout << arr[i] << " ";
}

Output:

Functors in C++

Related Topics

fread() Function in C++ Programming

C++ language is used to make high-performance applications that can work efficiently, and it is one of the world's most popular languages. It is an object-oriented and high-level programming language;...

3 minutes read.

Scope Resolution Operator vs this Pointer in C++

In this tutorial, we will compare the Scope Resolution operation to this Pointer in C++ language. Scope Resolution Operator The Scope Resolution Operator in C++ programming language is usually denoted by (::)....

3 minutes read.

Nullptr in C++

What is Nullptr in C++? A null pointer value is represented by the term nullptr. Use a null pointer value to indicate that a native pointer type, inner pointer, or object...

3 minutes read.

Singleton Design Pattern in C++

Singleton is similar to the global variable. Singleton helps to have only one object of its kind and provides only single access. One of the key features of the singleton...

2 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.

Pure Virtual Function in C++ With Example Program

What is a Virtual Function? A virtual function is created inside a class with the keyword virtual. A virtual function does not have any value to be returned. Once a virtual...

3 minutes read.

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations. C++ supports the four types of casting...

4 minutes read.

Difference between Two Sets in C++

The distinction between the two sets is made up of the components that are present in the first set but absent from the second set. The function consistently duplicates the...

3 minutes read.

Difference between "int main( ) and int main(void)" in C/C++

int main( ) function In the C/C++ programming language, int main() indicates a function that returns an integer at the end of the program execution. In general, a value of '0' indicates...

3 minutes read.

Ascending order in C++

In C++, the term "ascending order" refers to a specific order in which a list of elements is arranged. When a list of elements is arranged in ascending order, the...

3 minutes read.

Continue in C++ While loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the...

4 minutes read.

Top best IDEs for C/C++ Developers in 2024

Nothing in the current digital world is conceivable without programming. Everything needs programming, from the cell phones in our pockets to self-driving cars. Programming is also necessary for the mouse...

9 minutes read.

INT_MAX and INT_MIN in C/C++

In competitive programming, assigning a variable that maximum or minimum value a data type can carry is frequently necessary. Still, it might be challenging to recall such a significant, exact...

3 minutes read.

SDL library in C++ with Examples

SDL stands for Simple DirectMedia Layer. Using OpenGL and Direct3D, it is a cross-platform development library created to give users low-level access to audio, keyboard, mouse, joystick, and graphics hardware....

3 minutes read.

How to Reverse a String in C++ using Do-While Loop

Strings In C++, a string is an object that represents a group (or sequence) of various characters. Strings are part of the standard string class in C++ (std::string). The characters of...

4 minutes read.

abs() function in C++

In C++, the abs() function returns the absolute value of any integer number. Using this function a negative integer is multiplied by -1 and positive number or zero is returned...

4 minutes read.

Decimal to Octal in C++

We must create a software that converts a decimal number into an equal octal number given a decimal number as input i.e. convert a number having a base value of...

3 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is...

3 minutes read.