Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the penultimate element in a list?

Tags:

c++

stl

stdlist

I have a std::list<double> foo;

I'm using

if (foo.size() >= 2){     double penultimate = *(--foo.rbegin()); } 

but this always gives me an arbitrary value of penultimate.

What am I doing wrong?

like image 532
Paul Logue Avatar asked May 26 '17 16:05

Paul Logue


People also ask

How do I get the last second element in a list?

Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want second to last element in list, use -2 as index.

How do you slice the last element of a list in Python?

Get last item of a list by indexing. As the indexing in a list starts from 0th index. So, if our list is of size S, then we can get the last element of list by selecting item at index position S-1. It gives us the last item of list.


1 Answers

Rather than decrementing rbegin, you should increment it, as shown here:1

double penultimate = *++foo.rbegin(); 

as rbegin() returns a reverse iterator, so ++ is the operator to move backwards in the container. Note that I've also dropped the superfluous parentheses: that's not to everyone's taste.

Currently the behaviour of your program is undefined since you are actually moving to end(), and you are not allowed to dereference that. The arbitrary nature of the output is a manifestation of that undefined behaviour.


1Do retain the minimum size check that you currently have.

like image 154
Bathsheba Avatar answered Oct 14 '22 00:10

Bathsheba