1

filter_view does not have a const begin.

But I wonder why isn't there a member or free function on it that would return some_filter_view type that is that is same as filter_view except it has a const begin(). Obviously this method would be O(n), but it would be fine since it is explicit in code.

Is it just that it is too much work to standardize/ too big of a compile slowdown, or are there other reasons?

Basic example of what I would want:

void fn(){
    std::array<int,5> arr{1,2,3,4,5};
    const auto filtered = arr | std::views::filter([](auto){return true;});
    filtered.begin(); // does not compile
    // --would be nice if we could do 
    // const auto filtered = arr | std::views::filter([](auto){return true;}) | eval_begin;
    // --now filtered.begin() can be called
}
user438383
  • 5,716
  • 8
  • 28
  • 43
NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277

1 Answers1

3

This is basically "why can't we have a filter_view that caches on construction".

The answer is that it will make copies O(N) since the cached iterator are iterators into the original view, so your copied view have to find begin() again for its copy.

If you have a (non-const) filter_view already, then it's trivial to make a const-iterable view out of it with subrange. Obvious this requires the filter_view to be kept alive while the subrange is.

T.C.
  • 133,968
  • 17
  • 288
  • 421
  • why are cached iterators iterators into the view and not into original data? – NoSenseEtAl Oct 09 '21 at 15:18
  • 1
    `filter_view` adapts some arbitrary view `V`. It can only cache `V`'s iterators. – T.C. Oct 09 '21 at 15:21
  • I still don't get why that would make copy O(n)... but probably my understanding of view implementation is too naive. – NoSenseEtAl Oct 09 '21 at 15:48
  • 1
    The general rule is that an iterator into some view `v` isn't an iterator into a copy of `v`. This is true for containers, and it remains true for views. – T.C. Oct 09 '21 at 15:51