Functors

In C++, functors (function objects) are objects that act like functions and can be called using the function call syntax () like regular functions.

Functors are instances of classes that overload the operator() (call operator).

They are used to provide a functional interface and allow custom behavior in various contexts, such as STL algorithms, custom sorting criteria, and more.

Example of Functor:


Let’s demonstrate an example of creating a functor to compare two strings based on their lengths.

Functor C++ Code:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

// Functor to compare strings based on their lengths
struct LengthComparator {
    bool operator()(const std::string& str1, const std::string& str2) const {
        return str1.length() < str2.length();
    }
};

int main() {
    std::vector<std::string> words = {"apple", "orange", "banana", "grape", "kiwi"};

    // Sort the vector of strings using the LengthComparator functor
    std::sort(words.begin(), words.end(), LengthComparator());

    // Print the sorted vector
    for (const std::string& word : words) {
        std::cout << word << " ";
    }
    std::cout << std::endl;

    return 0;
}

Output:

kiwi grape apple orange banana

Explanation of the Code:
In this example, we create a functor LengthComparator that overloads the operator() to compare two strings based on their lengths. The functor takes two const std::string& arguments and returns a bool. It compares the lengths of the strings and returns true if the length of str1 is less than the length of str2.

We then use the std::sort algorithm to sort the vector of strings (words) using the LengthComparator functor as the comparison criterion. The sort algorithm rearranges the elements in the vector based on the custom sorting logic provided by the functor.

As a result, the vector words is sorted in ascending order of string lengths, and the sorted words are printed in the output.

Applications of Functors:


Functors are used in various scenarios where custom behavior is required, such as:

  • Sorting and searching with custom criteria.
  • Custom operations in STL algorithms.
  • Conditional transformations and data manipulations.
  • Filtering and selection in container operations.

Advantages of Functors:

  1. Flexibility: Functors allow you to define custom behavior in a single object, making it easy to change and reuse.
  2. Efficiency: Functors are generally more efficient than function pointers as they can be inlined by the compiler, resulting in better performance.
  3. Readability: Using functors can improve code readability by encapsulating custom logic within a named object.

Disadvantages of Functors:

  1. Slightly more complex: Compared to regular functions, functors require a class definition and overloading the operator(), which can add a little more complexity to the code.
  2. Specific use cases: For simple, short-lived operations, lambda functions might be a more concise and convenient option. Functors are best suited for more complex and reusable tasks.