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?