C++ bootcamp · Lab 34

Keep the evens

mediumLambdas12 minLesson: Lambdas

Read the question, write C++ on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

The first number is n, then n integers. Print only the even values, in the same order, space-separated.

Use a lambda with std::copy_if (or a range-for that calls a lambda predicate) so you practise the lambda syntax.

Input. n, then n integers.

Output. The even values, space-separated. If none, a blank line.

Constraints

  • 1 ≤ n ≤ 100

Examples

Example 1
Input
6
1 2 3 4 5 6
Output
2 4 6
Example 2
Input
3
1 3 5
Output
Hint
  1. auto even = [](int x) { return x % 2 == 0; };
  2. std::copy_if(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "), even);
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <iostream>
#include <vector>

int main() {
  int n;
  std::cin >> n;
  std::vector<int> v(n);
  for (int i = 0; i < n; i++) std::cin >> v[i];
  auto even = [](int x) { return x % 2 == 0; };
  for (int x : v) if (even(x)) std::cout << x << " ";
  std::cout << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.