Faken
Faken

Reputation: 11822

accessing a vector from the back

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?

Upvotes: 6

Views: 4585

Answers (3)

fingerprint211b
fingerprint211b

Reputation: 1186

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.

Upvotes: 5

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99665

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

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283783

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

myVector.end()[-2]

Upvotes: 7

Related Questions