How can I get the penultimate element in a list?

C++StlStdlist

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

The clearest way, in my mind, is to use the construct designed for this purpose (C++11):

double penultimate = *std::prev(foo.end(), 2)

Solution 3 - C++

I would just do *--(--foo.end()); no need for reverse iterators. It's less confusing too.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaul LogueView Question on Stackoverflow
Solution 1 - C++BathshebaView Answer on Stackoverflow
Solution 2 - C++Gregory CurrieView Answer on Stackoverflow
Solution 3 - C++user541686View Answer on Stackoverflow