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?
So, to iterate over a vector in reverse direction, we can use the reverse_iterator to iterate from end to start. vector provides two functions which returns a reverse_iterator i.e. vector::rend() –> Returns a reverse iterator that points to the virtual element before the start of vector.
Access an element in vector using operator [] element_reference operator[] (size_type n); element_reference operator[] (size_type n); element_reference operator[] (size_type n); It returns the reference of element in vector at index n.
C++ Vector Library - back() Function The C++ function std::vector::back() returns a reference to the last element of the vector. Calling back on empty vector causes undefined behavior.
If you want to access the last element of your vector use vec. back() , which returns a reference (and not iterator).
Not likely to be any faster, but this might look nicer:
myVector.end()[-2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With