Reputation: 127
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++?
Upvotes: 2
Views: 155
Reputation: 171177
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
.
Upvotes: 6