Access to the vector from the back

Is there a way to access a vector element starting from the back? I want to get the second second element. I am currently using the following for this:

myVector[myVector.size() - 2]

but it seems slow and awkward, is there a better way?

+5
source share
3 answers

Most likely it will be faster, but it may look better:

myVector.end()[-2]
+7
source

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

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

Vectors are created for quick random access, so your method is great too. Access to a vector element of any index is an O (1) operation.

+5
source

, , myVector.size() > 1.

0

All Articles