2

If I get a vector::end iterator, then push back a new element to the same vector, will what was the iterator to the end become an iterator to the last element?

If this does not work, is there an easy way of getting an iterator to the last element of a vector in C++?

3
  • 1
    If a reference will do instead of an iterator, back() returns a reference to the last element of a non-empty vector. Commented Jan 16, 2014 at 19:37
  • I'm using the iterators to do pointer arithmetic so that I can get the index of the element of the iterator by doing index = iterator_to_element - iterator_to_beginning Commented Jan 16, 2014 at 19:55
  • stackoverflow.com/q/6438086/560648 Commented Jan 16, 2014 at 20:37

1 Answer 1

6

That does not work - adding (or removing) elements of a std::vector invalidates all iterators into that vector. To get an iterator to the last element, you can use subtraction:

std::vector<T> vec;
vec.push_back(something);  //doing this so that the vector is not empty and the decrement is valid
auto itToLast = vec.end() - 1;

Depending on what you need to do, you might also consider rbegin(), which gives a reverse iterator to the last element (incrementing such an iterator moves it to the last-but-one, and so on).

Finally, subtraction only works on random access iterators (std::vector provides those, but e.g. std::list does not). For other iterators, you can use std::advance or std::prev.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.