STL Function Objects (Functors)

The Function Objects, also known as Functors, are the objects that behave like a function. It is due to the overloading of the ( ) parenthesis operator. The functors are defined inside the <functional> header file.

STL provides some predefined functors such as:

  1. equal_to
  2. not_equal_to
  3. greater
  4. less
  5. plus
  6. minus

Example

C++
// C++ program to illustrate some builtin functors
#include <functional>
#include <iostream>
using namespace std;

int main()
{
    // creating objects
    equal_to<int> eq;
    not_equal_to<int> neq;
    greater<int> gt;
    less<int> ls;
    plus<int> p;
    minus<int> m;

    // printing return values
    cout << "Functors and their return value\n";
    cout << boolalpha;
    cout << "equal_to, (10,20): " << eq(10, 20) << endl;
    cout << "greater, (10,20): " << gt(10, 20) << endl;
    cout << "less, (10,20): " << ls(10, 20) << endl;
    cout << "plus, (10,20): " << p(10, 20) << endl;
    cout << "minus(10,20): " << m(10, 20) << endl;

    return 0;
}

Output
Functors and their return value
equal_to, (10,20): false
greater, (10,20): false
less, (10,20): true
plus, (10,20): 30
minus(10,20): -10



C++ STL Cheat Sheet

The C++ STL Cheat Sheet provides short and concise notes on Standard Template Library (STL) in C++. Designed for programmers that want to quickly go through key STL concepts, the STL cheatsheet covers the concepts such as vectors and other containers, iterators, functors, etc., with their syntax and example.

Similar Reads

What is Standard Template Library(STL)?

The C++ Standard Template Library (STL) is a collection of generic class and function templates to provide some commonly used data structures and algorithms. It contains optimized and error-free code for useful containers such as vector, list, stack, queue, etc. It is a part of the standard library of C++ and...

Components of STL

C++ STL provides various components to make programming easier and more efficient. These components can be divided into four categories:...

STL Containers

The STL containers are the template classes to implement useful data structures such as dynamic arrays, hashmaps, linked lists, trees, etc. These containers allow programmers to store and manipulate data....

STL Iterators

Iterators are the objects used to iterate through the STL containers. They can be seen as pointers that are used to traverse and manipulate the data inside containers....

STL Algorithms

Algorithms are set of generic and optimal implementations of some useful algorithms to make programming easier and more efficient....

STL Function Objects (Functors)

The Function Objects, also known as Functors, are the objects that behave like a function. It is due to the overloading of the ( ) parenthesis operator. The functors are defined inside the header file....