Range-for over a sub-range

suggest change

Using range-based loops, you can loop over a sub-part of a given container or other range by generating a proxy object that qualifies for range-based for loops.

template<class Iterator, class Sentinel=Iterator>
struct range_t {
  Iterator b;
  Sentinel e;
  Iterator begin() const { return b; }
  Sentinel end() const { return e; }
  bool empty() const { return begin()==end(); }
  range_t without_front( std::size_t count=1 ) const {
    if (std::is_same< std::random_access_iterator_tag, typename std::iterator_traits<Iterator>::iterator_category >{} ) {
      count = (std::min)(std::size_t(std::distance(b,e)), count);
    }
    return {std::next(b, count), e};
  }
  range_t without_back( std::size_t count=1 ) const {
    if (std::is_same< std::random_access_iterator_tag, typename std::iterator_traits<Iterator>::iterator_category >{} ) {
      count = (std::min)(std::size_t(std::distance(b,e)), count);
    }
    return {b, std::prev(e, count)};
  }
};

template<class Iterator, class Sentinel>
range_t<Iterator, Sentinel> range( Iterator b, Sentinel e ) {
  return {b,e};
}
template<class Iterable>
auto range( Iterable& r ) {
  using std::begin; using std::end;
  return range(begin(r),end(r));
}

template<class C>
auto except_first( C& c ) {
  auto r = range(c);
  if (r.empty()) return r;
  return r.without_front();
}

without_front and without_back clamp count only when the iterator category is exactly std::random_access_iterator_tag. They then always call std::next or std::prev. A count that walks off any other range is undefined behavior. The if is not if constexpr, so those calls are compiled for every iterator type.

Now we can do:

std::vector<int> v = {1,2,3,4};

for (auto i : except_first(v)) {
  std::cout << i << '\n';
}

and print out

2
3
4

The temporary returned by except_first is the range-initializer, so range-based for extends its lifetime for the whole loop. Iterators into a temporary destroyed before the loop, or into a local inside a helper, still dangle.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents