1

I'm trying to understand some basic constructions with std::ranges like the Pythagorean triples examples of Niebler's blog. However, when I try the following baby example

#include <iostream>
#include <ranges>

template<class R, typename Fun>
auto for_each(R&& r, Fun f) {
    return std::forward<R>(r) | std::views::transform(std::move(f)) | std::views::join;
}

int main() {
    auto ints = for_each(std::views::iota(0,9), [](int i) {
            return std::ranges::single_view<int>{i};
            });

    for (auto k : ints | std::views::take(3)) {
        std::cout << k << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

The program prints gibberish. A random output is

0 731868824 0

This program simply takes a std::views::iota that would generate the numbers 0 through 8, and then for each integer i in this view it generates a std::ranges::single_view that has only the integer i in it. The implementation of for_each there should simply concatenate all those single views and then flatten them back, obtaining the original sequence of numbers 0 through 8.

What am I missing here?

xskxzr
  • 12,442
  • 12
  • 37
  • 77
Reimundo Heluani
  • 918
  • 9
  • 18
  • 1
    Duplicate of https://stackoverflow.com/questions/67282639 Your code prints `0 1 2` on GCC trunk. https://godbolt.org/z/81K8fcW8P – cigien Aug 19 '21 at 18:27
  • ohh nice thanks! I was about to post that if I change `single_view` for another like a `iota_view` it works fine. Tough to learn like this, been banging by head against this the whole afternoon – Reimundo Heluani Aug 19 '21 at 18:29

0 Answers0