Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterator for the last element of a vector

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.

like image 515
Yakov Avatar asked Sep 10 '13 14:09

Yakov


1 Answers

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.

like image 167
Daniel Frey Avatar answered Nov 01 '22 19:11

Daniel Frey