Algorithm Chaining in C++

Level 5291 keystrokes

copy_if keeps the even numbers from 1 to 10, then transform squares them in place. The result 4 16 36 64 100 is printed.

C++ code

// Input numbers 1 to 10
1vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Empty vector for the result
2vector<int> result;
3
// copy_if copies matching elements; back_inserter appends them with push_back
4copy_if(nums.begin(), nums.end(), back_inserter(result),
// Condition: keep even numbers
5 [](int n) { return n % 2 == 0; });
6
// Writing to result.begin() replaces each element in place
7transform(result.begin(), result.end(), result.begin(),
// Squares each number
8 [](int n) { return n * n; });
9
// Prints 4 16 36 64 100, each followed by a space
10for (int n : result) cout << n << " ";

Output

4 16 36 64 100 
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.

  • ,× 15
  • (× 11
  • )× 11
  • ;× 7
  • <× 6
  • .× 5
  • {× 3
  • }× 3
  • =× 3
  • _× 2

More C++ examples at level 5

← C++ typing practice