How can I get the penultimate element in a list?
Solution 1:
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:
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:
I would just do *--(--foo.end())
; no need for reverse iterators. It's less confusing too.