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?
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.