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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With