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:
- equal_to
- not_equal_to
- greater
- less
- plus
- minus
Example
// 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.
Contact Us