1

I want to implement range function to traverse container

template<class IterT> struct iteratorRange { IterT begin_; IterT end_; IterT begin() { return begin_; } IterT end() { return end_; } }; template<class T> iteratorRange<typename vector<T>::iterator>Head(vector<T> v, size_t step) { return {begin(v), next(begin(v), min(step, v.size()))}; } int main() { vector<int> v {1, 2, 3, 4, 5, 6, 7}; for (int& i : Head(v, 4)) { cout << i << ' '; } } 

I expected

1 2 3 4

But received

1103219 1109239 3 4

What is the error?

1
  • 4
    I think the problem is that vector<T> v is a copy and your iterators refer to that copy's elements. But the copy doesn't exist anymore when you cout. Commented Jan 31, 2020 at 20:53

1 Answer 1

2
template<class T> iteratorRange<typename vector<T>::iterator>Head(vector<T>& v, size_t step) { return {begin(v), next(begin(v), min(step, v.size()))}; } 

Instead of Head taking vector v by value, it should take a reference. This fixes your problem.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.