How do I get an iterator to the next-to-last element in a STL list without creating a temporary and modifying the list?
Is it possible to just say: --(--mylist.end())? Or would this change the end iterator of the list due to the prefix decrement?
How do I get an iterator to the next-to-last element in a STL list
Share
Please note that in general,
--mylist.end()is not guaranteed to compile for every container.For example, if you use a
std::vectororstd::arrayin release mode,mylist.end()is probably a raw pointer, and you cannot decrement a pointer returned by value from a function.A generic solution to this problem in C++11 is
std::prev(std::prev(mylist.end())), after checking that the list is long enough, of course. You need to#include <iterator>for this.