Filtering with a lambda in C++

Level 3136 keystrokes

isEven is a lambda that returns true for even numbers. The loop calls it for each element and prints only those that pass: 2 4 6.

C++ code

1vector<int> v = {1, 2, 3, 4, 5, 6};
// n % 2 == 0 is true when n is divisible by 2, i.e. even
2auto isEven = [](int n) { return n % 2 == 0; };
// Tests each element
3for (int n : v) {
// Prints only the even numbers: 2 4 6
4 if (isEven(n)) cout << n << " ";
5}

Output

2 4 6 
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.

  • ,× 5
  • <× 5
  • ;× 4
  • (× 4
  • )× 4
  • =× 4
  • {× 3
  • }× 3
  • "× 2
  • :× 1

More C++ examples at level 3

← C++ typing practice