Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing a vector from the back

Tags:

c++

vector

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?

like image 352
Faken Avatar asked Jun 16 '10 21:06

Faken


People also ask

How do you read a vector backwards?

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.

How do you access something in a 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.

What is vector back ()?

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.

How do I get vector back in C++?

If you want to access the last element of your vector use vec. back() , which returns a reference (and not iterator).


1 Answers

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

myVector.end()[-2]
like image 121
Ben Voigt Avatar answered Oct 09 '22 09:10

Ben Voigt