Fundamentals15 / 15
Up next

Filter and sum

#include <print>
#include <vector>
#include <ranges>

int main() {
    std::vector<int> nums{1, 2, 3, 4, 5, 6};
    int sum = 0;
    // keep the even numbers, then add them up
    for (int n : nums | std::views::filter([](int n) { return n % 2 == 0; })) {
        sum += n;
    }
    std::println("{}", sum);
}
What you're solving

compose ranges views over a vector