Search code examples
c++iteratorc++17

slice container with O(1) constructor from iterable begin and end


I have a forward iterator. I want a simple iterable container which wraps it and exposes begin() and end(). I.E.

template <typename C>
void use_container(C c) {
  std::cout << c.begin();
}
int main() {
std::vector<int> v {1,2,3,4,5,5};
auto begin_ = v.begin();
auto end_ = begin + 5;
use_container(/*create a container using the `begin_` and `end_` variables*/); 
return 0;
}

Is there such a std wrapper?


Solution

  • C++20 added this with std::ranges::subrange. For example the following will call use_container with a range that is a view over part of v:

    use_container(std::ranges::subrange{begin_, end_});
    

    Demo