Functor Class in C++

Level 5282 keystrokes

Multiplier overloads operator() so its objects can be called like functions. A Multiplier(3) is passed to transform, which triples every element: 3 6 9 12 15.

C++ code

// Functor: a class whose objects can be called like functions
1class Multiplier {
// State kept inside the object: the factor to multiply by
2 int factor;
3public:
// Constructor sets the factor
4 Multiplier(int f) : factor(f) {}
5
// Overloading operator() makes the object callable as triple(n)
6 int operator()(int n) const {
// Multiplies the argument by the stored factor
7 return n * factor;
8 }
9};
10
11vector<int> nums = {1, 2, 3, 4, 5};
// Functor that multiplies by 3
12Multiplier triple(3);
13
// transform calls triple(n) for each element and writes the result back into nums
14transform(nums.begin(), nums.end(), nums.begin(), triple);
// Prints 3 6 9 12 15
15for (int n : nums) cout << n << " ";

Output

3 6 9 12 15 
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • (× 10
  • )× 10
  • ,× 7
  • ;× 7
  • <× 5
  • {× 4
  • }× 4
  • :× 3
  • .× 3
  • "× 2

More C++ examples at level 5

← C++ typing practice