Composability of STL algorithms

后端 未结 4 1308
星月不相逢
星月不相逢 2021-02-02 06:44

The STL algorithms are a pretty useful thing in C++. But one thing that kind of irks me is that they seem to lack composability.

For example, let\'s say I have a v

4条回答
  •  滥情空心
    2021-02-02 07:25

    Not sure if this is still active, but... A new light wait header only lib that does what you describe. Doc talks about lazy evaluation and com compossible generators.

    Doc snippet:

    • Read in up to 10 integers from a file "test.txt".
    • filter for the even numbers, square them and sum their values.
        int total = lz::read(ifstream("test.txt")) | lz::limit(10) |
                    lz::filter([](int i) { return i % 2 == 0; }) |
                    lz::map([](int i) { return i *  i; }) | lz::sum();
    

    you can split that line up into multiple expressions.

        auto numbers = lz::read(ifstream("test.txt")) | lz::limit(10);
        auto evenFilter = numbers | lz::filter([](int i) { return i % 2 == 0; });
        auto squares = evenFilter | lz::map([](int i) { return i *  i; });
        int total = squares | lz::sum();
    
    • Even though this expression is split over multiple variable assignments, it is not any less efficient.
    • Each intermediate variable simply describes a unit of code to be executed. All held in stack.

    https://github.com/SaadAttieh/lazyCode

提交回复
热议问题