• IMPORTANT: Welcome to the re-opening of GameRebels! We are excited to be back and hope everyone has had a great time away. Everyone is welcome!

C++ Range-Based For Loop Iterator Wrapper

bitm0de

Active Member
Joined
May 24, 2015
Messages
13
Reaction score
0
Currently the range based for loop doesn't allow you to directly change the range in which it iterates. It simply iterates from begin() to end(). My wrapper class I created simply changes the semantics of what begin() and end() are to allow you to modify this range without reverting to the alternative full for loop syntax. I also use type deduction to make the template parameters implied so that you don't have to know what kind of iterators they are. :)

Code:
#include <iostream>
#include <vector>

template<typename Iter>
class range_iterator
{
  public:
    range_iterator(Iter iter_begin, Iter iter_end)
      : _begin(iter_begin), _end(iter_end)
    { }

    Iter begin() const { return _begin; }
    Iter end()   const { return _end; }

  protected:
    Iter _begin;
    Iter _end;
};

template <class Iter>
range_iterator<Iter> make_range_iterator(Iter begin, Iter end)
{ return range_iterator<Iter>(begin, end); }

int main()
{
  std::vector<int> v { 1, 2, 3, 4, 5 };
  auto range_iter = make_range_iterator(v.begin() + 2, v.end() - 1);
  for (auto &x : range_iter)
  {
    std::cout << x << std::endl;
  }
}
 
Top