This is pretty trivial to do (though I'd 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 it stands right now, this follows normal C++ conventions (0-based counting, the end you specify is past the end of the range, not in it) so to get the output you asked for, you'd specify a range of 3, 7
, like:
for (int num : make_range(vector, 3, 7))
std::cout << num << ", "; // 4, 5, 6, 7,
Note that the range-based for
loop knows how to use begin
and end
member functions to tell it the range it's going to iterate, so we don't have to deal with invalidating iterators or anything like that, we just have to specify the beginning and end of the range we care about.