Reputation: 7699
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?
Upvotes: 0
Views: 1728
Reputation: 227390
You could use std::advance and a reverse_iterator:
SomeContainerType::reverse_iterator it = myList.rbegin();
std::advance(it, 1); // next to last element
This works even if the iterator type in question does not support operator+
.
Upvotes: 3
Reputation: 263118
Please note that in general, --mylist.end()
is not guaranteed to compile for every container.
For example, if you use a std::vector
or std::array
in 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.
Upvotes: 3