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
C++ Lambda Expressions
C++ Move Semantics and the Rule of Five
Modern C++ Features: ranges, optional, variant and format
C++ Multithreading: thread, mutex and async
Exercises & Assignments
Filter and sum numbers with algorithms and ranges
Interview Questions & Answers
What is the Rule of Three, Five and Zero in C++?
What does std::move do in C++?
What are concepts in C++20?
What is perfect forwarding in C++ (std::forward)?
How do lambda captures work in C++?
What is new in C++20?
What is new in C++23?