I need to get an iterator to the last element in a std::vector
.
As known end()
method returns an iterator referring to the past-the-end element in the vector container. Can I implement what I need by using end() - 1
?
As far as I understand I can't use back()
method, since it returns a reference.
Given that you know/have checked that the vector is not empty and C++11 is an option, you can use std::prev:
auto it = std::prev( your_vector.end() ); // or .cend() if a const_iterator is OK
Also note that using rbegin()
returns a reverse iterator, which is different from a normal iterator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With