auto ResultView
{
std::views::iota(1,30)
| std::views::take(20)
| std::views::filter([](int x){ return x%2!=0; })
};
std::cout<<ResultView[2];
I've obviously got something wrong with the filter line, but can't for the life of me figure out what. Please help!
Error msg from clang++ (19.1.7): error: no viable overloaded operator[] for type 'invoke_result_t<__range_adaptor_closure_t<__bind_back_t<__fn, tuple
In your example, you have to see the view as something you can iterate from the first to the last item but without the possibility to directly access to one specific item as you do with operator[]
(that's the meaning of the error you get, in other words, you don't have random access).
If you want to have this possibility, you could have from your view something that has this operator, like a std::vector
for instance. And you can do that easily with the std::ranges::to
function:
#include <ranges>
#include <vector>
#include <iostream>
int main (int argc, char** argv)
{
auto res
{
std::views::iota(1,30)
| std::views::take(20)
| std::views::filter([](int x){ return x%2!=0; })
| std::ranges::to<std::vector>()
};
std::cout << res[2] << "\n";
}