×

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

C++ Program to find largest subarray with 0 sum

Write a program to find the largest subarray that has a sum zero. The array contains positive and negative numbers. Print the length of the max subarray whose sum turns...

4 minutes read.

Splitting a string in C++

Any programming language must have the ability to work with string data. For programming needs, we sometimes need to separate string data. Many computer languages provide a split() method that...

4 minutes read.

C++ Variable

In this article, we will discuss variables in C++ with their types and examples. What are Variables? Variables are specific memory storage spaces that hold a value. During the execution of a...

4 minutes read.

Default arguments in C++

Arguments in a function are defined as the values supplied when the function is called. The source is the values supplied, and the destination is the receiving function. Let us...

3 minutes read.

Difference between OOP and POP in C++

Object-Oriented Programming (OOP) Prioritizes data over methods (functions) and treats data as an essential component of program development.  OOP prohibits the free flow of data throughout the system. Tighter ties to data manipulation...

4 minutes read.

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or...

4 minutes read.

Stack in C++

Stack: The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract...

4 minutes read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

C++ storage classes

Storage Classes are used to characterize a variable's or function's characteristics. These characteristics include scope, visibility, and life-time, which allow us to track the presence of a variable over the...

5 minutes read.

How to concatenate two strings in C++

In the C++ programming language, the concatenation of two or even more strings is covered in this section. The term "string concatenation" refers to a collection of characters that join two...

4 minutes read.

C++ Program to Print Fibonacci Triangle

Fibonacci Triangle Program in CPP Definition: Fibonacci Triangle as the name suggests is the same as the Fibonacci number series where the next element is the sum of the previous two elements....

3 minutes read.

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute read.

New Operator in C++

Dynamic memory allocation in C++ means manually allocating the memory by the developer duing run-time. The dynamic memory is allocated in the heap section of the RAM, whereas the static...

3 minutes read.

Destructor

Let’s discover the C++ destructor, virtual and pure virtual destructors, and when destructors are invoked and their rules in this lesson. Destructors : A member function that destroys an object is known as...

5 minutes read.

Type difference of Character literals in C VS C++

Character literals in C: In C, a character literal is represented by a single character enclosed in single quotes, such as 'a' or 'b'. It is of type int. This means...

5 minutes read.

Single Handling in C++

Introduction: Single handling in C++ refers to a technique for processing multiple events or requests with a single function or handler rather than creating separate functions for each task. This allows...

5 minutes read.

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.

The Stock Span Problem

It is necessary to determine the span of a stock's price throughout all n days in order to solve the stock span problem, which involves a set of n daily...

5 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.