#include <iostream>
#include <vector>
#include <ranges>
int main()
{
std::vector<int> ints {1, 2, 3, 4, 5};
auto isEven = [] (const auto& element)
{
return element % 2 == 0;
};
auto even = ints | std::views::filter(isEven);
for (auto& element : even)
{
++element;
}
for (const auto& element : ints)
{
std::cout << element << "\n";
}
std::cout << "\n\n";
// Interesting things start further...
for (auto& element : even)
{
++element;
}
for (const auto& element : ints)
{
std::cout << element << "\n";
}
return 0;
}
The output:
1
3
3
5
5
1
4 // Interesting...
3
5
5
Did you notice this second 4
in the second output? How did it end up there? It seems that happened due to even.begin()
has been cached during the first iteration over the view, and the view is not correct anymore because of that as it always starts with the same element regardless of the actual value of *even.begin()
.
Does that mean that views are not supposed to be reused? But why caching then?