std::function in C++

Level 4228 keystrokes

A std::function<int(int, int)> variable holds three different lambdas in turn; calling it with 5 and 3 prints 8, 15 and 2.

C++ code

// op can hold any callable that takes two ints and returns an int
1function<int(int, int)> op;
// Store an addition lambda
2op = [](int a, int b) { return a + b; };
// 5 + 3: prints 8
3cout << op(5, 3) << endl;
// Replace it with a multiplication lambda
4op = [](int a, int b) { return a * b; };
// 5 * 3: prints 15
5cout << op(5, 3) << endl;
// Replace it with a subtraction lambda
6op = [](int a, int b) { return a - b; };
// 5 - 3: prints 2
7cout << op(5, 3) << endl;

Output

8
15
2
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.

  • <× 13
  • ;× 10
  • ,× 7
  • (× 7
  • )× 7
  • [× 3
  • ]× 3
  • {× 3
  • }× 3
  • =× 3

More C++ examples at level 4

← C++ typing practice