Filter and sum numbers with algorithms and ranges

Description: From the numbers 1 to 10: keep the even ones, square them, print them and print the sum.

Hint:

  • std::views::filter and std::views::transform, and std::accumulate.

Solution

#include <iostream>
#include <numeric>
#include <ranges>
#include <vector>

int main() {
    auto squares = std::views::iota(1, 11)
                 | std::views::filter([](int n) { return n % 2 == 0; })
                 | std::views::transform([](int n) { return n * n; });

    int sum = 0;
    for (int x : squares) {
        std::cout << x << ' ';
        sum += x;
    }
    std::cout << '\n' << "Sum: " << sum << '\n';
}
Output

4 16 36 64 100
Sum: 220

How it works

  • iota(1, 11) makes the numbers 1 to 10, and the pipeline filters and changes them lazily.

Read Modern C++ Features.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.