9

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.

1

5 Answers 5

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Very helpful - I just discovered the issue with rbegin() returning a reverse iterator, when I tried assigning the result to a forward iterator. Thanks
9

The easiest is probably your_vec.rbegin().

2 Comments

the iterators' type don't match.
@athos: Doesn't match...what? He simply asked for an iterator to the last element, and rbegin() provides that. If you want some non-reverse iterator to the last element, well, perhaps you should ask a question about that; it's clearly a different question than the OP asked here though.
3

Thats the rbegin() iterator. For example:

int main() { std::vector<int> v = {0,1,2,3}; for(auto& it = v.rbegin() ; it != v.rend() ; ++it) std::cout << *it << " "; } 

The output is:

3 2 1 0

2 Comments

LOL I was reading the documentation I linked about std::rbegin() and I just noticed that feature is since C++14.
I always use std::begin(), so using std::rbegin() was a natural reflex action, even if it doesn't exist yet :)
0

What do you need the iterator for? If it is for iterating from back to front, you can use the reverse iterators (rbegin, rend). If it is a function which expects an iterator (for example, because you want it to iterate through all but the last element), then you can use end() - 1 on a vector. This will only work on random access iterators, however; for other types, you will need std::prev (if you've got C++11) or the equivalent from your toolkit (pre C++11):

template <typename BidirectionalIterator> BidirectionalIterator prev( BidirectionalIterator it ) { -- it; return it; } 

(If you don't have it already, and aren't using C++11, add it to your toolkit.)

Comments

0

You can use reverse_iterators. vec.rbegin() will give you a reverse_iterator pointing at the last element in the vector. More about it: http://en.cppreference.com/w/cpp/iterator/reverse_iterator

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.