#include <ranges> #include <numeric> #include <vector> #include <iostream> int main() { std::vector<int> vec = {1, 2, 3}; // map, using `std::views::transform`. Implemented in C++20 for(int elem : std::views::transform(vec, [](int x) { return x + 1; })) { std::cout << elem << " "; // 2 3 4 } std::cout << "\n"; // `std::ranges::fold_left` will be available with C++23. // Until then, we're stuck using the <numeric> iterator version, which was // implemented in C++20. std::cout << std::accumulate(vec.begin(), vec.end(), 1, [](int x, int y) { return x * y; }) << "\n"; // 6 return 0; }
$ g++ --std=c++20 test.cpp $ ./a.out 2 3 4 6
#include <algorithm> #include <functional> #include <iostream> #include <numeric> #include <ranges> #include <vector> int main() { std::vector<int> vec{1, 2, 3, 4, 5}; auto plus_one{[](const auto x) { return x + 1; }}; std::ranges::for_each(vec | std::views::transform(plus_one), [](const auto x) { std::cout << x << " "; }); std::cout << "\n"; std::cout << std::accumulate(std::begin(vec), std::end(vec), 1, std::multiplies<>()) << "\n"; return 0; }