I am trying to understand the sequence of calls to filter functions when passed through pipe operators (views/adapters). The result I see is not intuitive at all. While there might be reasons for it, I'd appreciate if someone can walk this through. As well if one can point to right documentation on cppreference.com.
#include <vector>
#include <ranges>
#include <iostream>
int main() {
const auto vec = std::vector{1,2,3,4,5,6};
auto filter = [](const auto f) {
std::cout << "f = " << f << ", ";
return f % 2 == 0;
};
std::cout << std::endl;
for (auto v : vec
| std::views::reverse
| std::views::filter(filter)
| std::views::take(2)
| std::views::reverse)
{
std::cout << std::endl << "v = [" << v << "]" << std::endl;
}
}
Actual result:
f = 6, f = 5, f = 4, f = 3, f = 2, f = 3, f = 4,
v = [4]
f = 3, f = 4, f = 5, f = 6,
v = [6]
f = 5, f = 6,
Expected result:
f = 6, f = 5, f = 4, f = 3, f = 2, f = 1,
v = [4]
v = [6]
Here is the godbolt sample for code above. And here is some more code, I tried to break it down to understand. But nothing strikes out as obvious.