tags:

views:

127

answers:

3

Is there a way to access an element on a vector starting from the back? I want to access the second last element.currently I'm using the following to achieve that:

myVector[myVector.size() - 2]

but this seems slow and clunky, is there a better way?

+4  A: 

Not likely to be any faster, but this might look nicer:

myVector.end()[-2]
Ben Voigt
Or `myVector.rbegin()[1]`.
Pavel Minaev
@Pavel: I like that solution the best, it makes the most sense and looks very clean.
Faken
Note that Ben's point about this not really being any faster still applies, however.
Pavel Minaev
Is this portable? Is `std::vector::iterator` required to overload the index operator? It will usually work, as `std::vector::iterator` is usually a typedef'd pointer. But, is it guaranteed?
caspin
@Caspin: Yes. `std::vector` provides random access iterators, and that's one of the properties of a random access iterator.
Dennis Zickefoose
+4  A: 

Well you can always use vector::back(). If you want to iterate from the back, use the reverse_iterator :

vector<something>::reverse_iterator iter = v.rbegin();
iter++; //Iterates backwards

Vectors are made for fast random access, so your way is just fine too. Accessing a vector element at any index is an O(1) operation.

fingerprint211b
vector<something>::reverse_iterator iter = v.rbegin();
Andrei
Thanks, fixed it.
fingerprint211b
A: 

Your way is perfectly valid and pretty fast except that you should check myVector.size() > 1.

Kirill V. Lyadvinsky
Or i could do it like myvector.at(myVector.end - 2) and make it even slower.
Faken
`at` uses exceptions to indicate out-of-range error. I'd not use it in this simple case.
Kirill V. Lyadvinsky