简体   繁体   中英

Vector iterators in C++

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++?

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 eg std::list does not). For other iterators, you can use std::advance or std::prev .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM