Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
C++ Range-Based For Loop Iterator Wrapper
#1
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. Smile

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;
  }
}


Forum Jump:


Users browsing this thread: 1 Guest(s)


Powered by © 2002-2020 MyBB Group.
Theme by CreWix. Fixed by Tomik. Customized for Aeowulf.