C++20 added the ranges library, one part of which is std::ranges::subrange
. This can be used as a view into a std::vector
very similarly to how std::string_view
is used as a view into a std::string
.
This is much better than passing a vector by reference along with indices, or passing a pair of iterators.
std::ranges::subrange<Iterator>
has a template argument which is the iterator type. Use this declaration to avoid typing a mouthful everytime:
template <typename T>
using Range<T> = std::ranges::subrange<typename std::vector<T>::iterator>;
Note that if using reverse iterators of a vector, it has a different type, so define another type with iterator as std::vector<T>::reverse_iterator
.
std::vector<int> vec;
// Construction
Range<int> range{vec.begin(), vec.end()};
// Now, we can use range.begin(), range.end() etc.
// Construct a new subrange from this using iterators
range.advance(n);
// Advance begin iterator of range by n (can be negative as well)