This is pretty trivial (although I would call the result a range, not an iterator).
A simple implementation would look something like this:
template <class Iter> class range { Iter b; Iter e; public: range(Iter b, Iter e) : b(b), e(e) {} Iter begin() { return b; } Iter end() { return e; } }; template <class Container> range<typename Container::iterator> make_range(Container& c, size_t b, size_t e) { return range<typename Container::iterator> (c.begin()+b, c.begin()+e); }
As of now, this follows normal C ++ conventions (counting based on 0, the end you specify is outside the end of the range, not in it), so to get the result you requested, you must specify range 3, 7 , for example:
for (int num : make_range(vector, 3, 7)) std::cout << num << ", "; // 4, 5, 6, 7,
Note that in a range-based for loop, we know how to use the begin and end member functions to tell it the range in which it will go, so we donβt need to deal with invalid iterators or something like what we just need indicate the beginning and end of the range we care about.
Jerry Coffin
source share