Iterator to last element in std::list

#include <list>
using std::list;

int main()
{
    list <int> n;
    n.push_back(1);
    n.push_back(2);
    n.push_back(3);

    list <int>::iterator iter = n.begin();
    std::advance(iter, n.size() - 1); //iter is set to last element
}

is there any other way to have an iter to the last element in list?


Solution 1:

Yes, you can go one back from the end. (Assuming that you know that the list isn't empty.)

std::list<int>::iterator i = n.end();
--i;

Solution 2:

Either of the following will return a std::list<int>::iterator to the last item in the list:

std::list<int>::iterator iter = n.end();
--iter;

std::list<int>::iterator iter = n.end();
std::advance(iter, -1);

// C++11
std::list<int>::iterator iter = std::next(n.end(), -1);

// C++11
std::list<int>::iterator iter = std::prev(n.end());

The following will return a std::list<int>::reverse_iterator to the last item in the list:

std::list<int>::reverse_iterator iter = std::list::rbegin();

Solution 3:

With reverse iterators:

iter = (++n.rbegin()).base()

As a side note: this or Charles Bailey method have constant complexity while std::advance(iter, n.size() - 1); has linear complexity with list [since it has bidirectional iterators].