Browsing index pages (4 articles)
↧
How can I get the penultimate element in a list?
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?
View ArticleAnswer by Bathsheba for How can I get the penultimate element in a list?
Rather than decrementingrbegin, you should increment it, as shown here:1double penultimate = *++foo.rbegin();as rbegin() returns a reverse iterator, so ++ is the operator to move backwards in the...
View ArticleAnswer by user541686 for How can I get the penultimate element in a list?
I would just do *--(--foo.end()); no need for reverse iterators. It's less confusing too.
View ArticleAnswer by Gregory Currie for How can I get the penultimate element in a list?
The clearest way, in my mind, is to use the construct designed for this purpose (C++11):double penultimate = *std::prev(foo.end(), 2)
View Article
Browsing index pages (4 articles)