ritter
ritter

Reputation: 7699

STL list access to next-to-last element

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

Answers (3)

juanchopanza
juanchopanza

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

fredoverflow
fredoverflow

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

Nim
Nim

Reputation: 33655

if okay with a reverse_iterator, then: some_list.rbegin() + 1;

Upvotes: 2

Related Questions