Access second to last element of Vector Array

Hi, so i started (Re-)learning C++ a while ago (My original knowledge was very limited anyway), and i need to be able to read the last, and second-to-last elements of a Vector Array.
Now, i found that i can use MyArray.Back() to get the last element...
But after searching the web all day, i just couldn't find a way to do something like MyArray.back() -1. (which just gives the contents of the last element -1!

I eventually just reversed the array, and addressed and incremented the standard way:-
MyArray [0], and then i++ to give MyArray[1] (giving me the last and second to last element).
But perhaps this is not efficient, and certainly not 'elegant'.
So my question is, is there in fact a way to do MyArray.back() but count backwards from the last element given?

Thanks.
Vector Array

Those are two different things. Which is it? A vector, or an array?

If you want the second-to-last element of a vector theVector[theVector.size()-2] will give you that.

MyArray [0], and then i++ to give MyArray[1]
You don't have to start reading at zero. You can read any element you like. If the vector is size 4, you can read MyArray[0] and myArray[1] and myArray[2] andmyArray[3] at any time, in any order.
Last edited on
Thankyou for the reply Repeater.

Sorry for my confusion over 'Vector' and 'Array'. They seem so similar (ok one is fixed and one is not) There's a lot for me to learn :)

So, back to it. In a previous iteration of my 'program' i was in fact using 'size', but then i recently noticed that it no longer seemed to be 'working'. Strange, because i'd previously tested it as working...cue 'headache'.

Its all about syntax though isn't it, and it is possible that somewhere along the way i accidentally changed it somehow...

I read from zero, because in an effort to achieve my goal, i used the REVERSE function to reverse the Vector, so that by then counting from zero, i was in fact accessing the last and second-to-last element of the Vector. (It was all i could think of).

I do see what you mean though regarding accessing. A silly mistake by me. I did at one point try using a pointer and incrementing, but then realised it would be easier to just access the elements directly.

Edit: So, previously i was using MyVector.size()-1;

Which obviously doesn't work!

Again, thankyou for your help!
Last edited on
Topic archived. No new replies allowed.