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
.