Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the code for the second to last element in a vector

Tags:

c++

I am trying to build a program that uses the second to last element in a vector, so far I've used: (arr2.rbegin()+1)

If I use a comparison operator in a conditional such as:

if(arr2.rbegin()+1 == true)  

I get an error message: 'no match for operator =='

like image 283
Person Avatar asked Aug 30 '13 19:08

Person


People also ask

How do you increment an element in a vector?

Read a value into x , use that value as index into the vector, and increase the value at that index. So if the input for x is 1 , then it's equivalent to vec[1]++ , that is the second (remember that indexes are zero based) will be increased by one.


2 Answers

Many of the answers and comments have the right idea but really ugly syntax. Here are two nice ways to express that.

arr2.end()[-2] // end() is past the last element, -1 for last element, -2 for second-last arr2.rbegin()[1] // rbegin() is reverse order starting at 0 for last element, 1 for second-last 

Demo: http://ideone.com/2cZeUq

It works because RandomAccessIterator, which vector has, is required to provide operator[] such that it[n] is equivalent to *(it + n), just like for pointers.

So the code in your question becomes just

if (arr2.rbegin()[1]) // test penultimate element 
like image 107
Ben Voigt Avatar answered Oct 01 '22 10:10

Ben Voigt


looking at the documentation here

http://www.cplusplus.com/reference/vector/vector/?kw=vector

I'd expect you to access your element by

secondToLast = myVector[myVector.size() - 2]; 
like image 37
Sam I am says Reinstate Monica Avatar answered Oct 01 '22 10:10

Sam I am says Reinstate Monica