| by Arround The Web | No comments

Functor C++ Examples

A C++ class that operates like a function is called a functor. The identical old function call syntax is used to invoke the functors. We create an object that overloads the “operator()” to generate a functor. We can also say that the objects that may be interpreted as either a function or a function pointer are called functors. When modeling the functional effects using the values of parametric data types, “functors” are extremely convenient. In this article, the functor concept will be studied in detail along with C++ codes.

Example 1:

The “iostream” is the header file that we include here because we have to utilize the functions that are declared in this header file. The “iostream” header file contains a function declaration. The “std” namespace is also added here. Then, we generate a class called “FunctorClass”. Below this, we type “public” which is the public constructor here and place the “operator()” function. Then, we place a sentence that we want to render on the screen in the “cout” statement.

After this, we call the “main()” function and then create the object of the “FunctorClass” with the name, “my_functor”. Here, we call the “my_functor()” function so it displays the statement that we added below the “operator()” function.

Code 1:

#include <iostream>
using namespace std;
class FunctorClass {
    public:
        void operator()() {
            cout << "The Operation is called here";
        }
};
int main() {
    FunctorClass my_functor;
    my_functor();

    return 0;
}

Output:

The line that we added in the “operator()” function of the “FunctorClass” is displayed here by utilizing the “my_functor” functor object.

Example 2:

We include the “iostream” header file here because some function declaration is contained in the “iostream” header file. The “std” namespace is also inserted. Next, we create a class named “SquareClass”.

Below that, we type “public” which is the public constructor and position the “operator()” function of the “int” data type beneath it. We pass the “val” variable of the “int” data type to this “operator()” function. This function returns the multiplication result as we inserted “val * val” in the “return()” function below the “operator()” function.

Now, the “main()” function is called here. Then, the object is created here with the name “s_functor” of the “SquareFunctor” class. Then, we utilize the “cout” which aids in rendering the information.  After this, we call the “my_functor()”object here like a function and it returns the multiplication result of “5 * 5” as we added “5” as the parameter while calling it.

Code 2:

#include <iostream>
using namespace std;
class SquareClass {
    public:
        int operator()(int val) {
            return (val * val);
        }
};
int main() {
    SquareClass s_functor;
    cout << "The square of the given value is " << endl;
    cout << s_functor(5);

    return 0;
}

Output:

We get the output after calling the “my_functor” object of the “SqaureClass” class like the “my_functor()” function and then passing “5”. We get “25” as the square of the number “5”.

Example 3:

The “iostream” header file is included here because it contains a function declaration, and the “std” namespace is introduced afterward. The “ProductFunctor” class is then made. The public constructor, “public”, is typed below it and the “operator()” function of the “int” data type is positioned underneath it. We override this function here and pass two parameters into it: “int var1” and “int var2”.

Then, we utilize the “return” below this and multiply both variables which return the multiplication result of both numbers “var1 * var2”.  The “main()” function is then called here and we generate the class object with the name “P_functor” of the “ProductFunctor” class. Then, we initialize a new variable with the name “pro_result” and assign the “P_functor” object as the “P_functor()” function after calling it.

We pass “28” and “63” as the parameter. This will multiply both values and save the result in the “pro_result” variable that we print below this using the ”cout” and passing “pro_result” in it.

Code 3:

#include <iostream>
using namespace std;
class ProductFunctor {
    public:
        int operator()(int var1, int var2) {
            return var1 * var2;
        }
};
int main() {
    ProductFunctor P_functor;
    int prod_result = P_functor(28, 63);
    cout << "The product is : " << prod_result << endl;
    return 0;
}

Output:

We get the product after calling the “P_functor” object as the “P_functor()” function and passing the values to it. The product of those values is “1764”.

Example 4:

The “GreetingFunctorClass” is generated in this instance. Then, we insert the “public” constructor and override the “operator()” function in this “public” constructor. We type “Hello! I’m a C++ Programmer here” after placing the “cout” underneath the “operator()” function.

Now onwards, we call the “main()”. We create the “g_functor” here as the object of the “GreetingFunctorClass” and then call this “g_functor” object as the “g_functor()” function. This gives the outcome that we added in the “operator()” function while overriding it.

Code 4:

#include <iostream>
using namespace std;
using namespace std;
class GreetingFunctorClass {
  public:    
    void operator()() {
      cout << "Hello! I'm a C++ Programmer here";
    }
};
int main() {
  GreetingFunctorClass g_functor;
  g_functor();
  return 0;
}

Output:

Here, we might notice that the statement that we added when we overrode the “operator()” function in our code is displayed here as we call the class object like a function.

Example 5:

The “bits/stdc++.h” is included this time as it contains all necessary function declarations. Then, the “std” namespace is placed here. The class that we create here is the “incrementFunctor” class. Then, we create a “private” constructor and initialize the “int_num” variable with the “int” data type.

Underneath this, the “public” constructor, we place the “incrementFunctor” and pass “int n1” inside it. Then, we type “int_num(n1)” after placing the “:”. Then, we override the function which is the “operator()” function of the “int” data type and declare “int arrOfNum” here. We then use the “return” and insert “int_num + arrOfNum”. Now, this increments the values of “arrOfNum”, adds the “int_num” value into them, and returns them here.

After invoking the “main()”, we initialize the “arrOfNum” and assign different integer values here. Then, the “n1” variable is initialized where we add the “sizeof” function like “sizeof(arrOfNum)/sizeof(arrOfNum[0])”. After this, the “additionNumber” is then initialized with “3”. Now, we utilize the “transform()” function. This “transform()” is the same as creating the object of the “increamentFunctor” class and then calling its object.  After this, we use the “for” loop and then “cout” the “arrOfNum[i]”.

Code 5:

#include <bits/stdc++.h>
using namespace std;
class incrementFunctor
{
private:
    int int_num;
public:
    incrementFunctor(int n1) : int_num(n1) { }
    int operator () (int arrOfNum) const {
        return int_num + arrOfNum;
    }
};
int main()
{
    int arrOfNum[] = {6, 3, 2, 1, 9, 0, 8};
    int n1 = sizeof(arrOfNum)/sizeof(arrOfNum[0]);
    int additionNum = 3;
    transform(arrOfNum, arrOfNum+n1, arrOfNum, incrementFunctor(additionNum));

    for (int i=0; i<n1; i++)
        cout << arrOfNum[i] << " ";
}

Output: 

The outcome of the code is shown here in which “incrementFunctor” is the “Functor” that is utilized as the function.

Example 6:

In this code, we utilize the predefined “greater” functor. Here, we include four different header files as we require them in our code because the functions or methods that we need in our code are declared in them. Then, after adding “std” and then calling the “main()”, we initialize the “myIntegerVector” vector. We insert some unsorted values in this vector. Below this, we apply the “sort” function to sort these vector values.

When we utilize this function, it sorts the values in ascending order. But we utilize the “greater” here which is the predefined function in C++ which gives the result of sorting in a descending manner. After this, we display the sorted values with the aid of “for” loop and then “cout”.

Code 6:

#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;

int main() {
    vector<int> myIntegerVector = {13, 21, 19, 44, 32, 42, 9, 6};
    sort(myIntegerVector.begin(), myIntegerVector.end(), greater < int > ());
    for (int vec_num: myIntegerVector) {
        cout << vec_num << "  ";
    }
    return 0;
}

Output:

All the values of the vector are sorted in a descending manner with the aid of the predefined functor in C++ which is the “greater” functor, and its definition is available in the “functional” header file.

Conclusion

The concept of the “functor C++” is deeply explored in this article. We studied that an object can be invoked as a function to overload a function called “operator()”. This is known as a functor. Public access must be provided for the overloading of the “operator()” to be utilized as intended. We illustrated different examples in which we utilized the “functors” and the predefined “functor” in our code.

Share Button

Source: linuxhint.com

Leave a Reply