Hacker News new | past | comments | ask | show | jobs | submit login

You'll like the `std::ranges` library that's been somewhat implemented as of C++20 and is getting some more stuff in C++23. It's very Fun!

    #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;
    }
Building and running with the following:

    $ g++ --std=c++20 test.cpp
    $ ./a.out
    2 3 4
    6



There's a nicer way still:

    #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;
    }
https://godbolt.org/z/84ePjfPhf




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: