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开发者_Python百科 better way?
Not likely to be any faster, but this might look nicer:
myVector.end()[-2]
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.
Your way is perfectly valid and pretty fast except that you should check myVector.size() > 1
.
精彩评论