tags:

views:

218

answers:

5
#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?

+7  A: 

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;
Charles Bailey
A: 

Take the end() and go one backwards.

list ::iterator iter = n.end(); cout << *(--iter);

Mitten.O
+1  A: 

Both std::list::back() and std::list::rbegin() return an iterator to the last item in the list.

Remy Lebeau - TeamB
`back()` returns a reference to the last element, not an iterator to the last element; `rbegin()` returns a reverse iterator, not an iterator.
James McNellis
A reverse iterator is an iterator. Its just not a list::iterator.
Dennis Zickefoose
@Dennis: Which is what I meant; sorry if it wasn't clear.
James McNellis
A: 

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].

Eugen Constantin Dinca
A: 

You could write your own functions to obtain a previous (and next) iterator from the given one (which I have used when I've needed "look-behind" and "look-ahead" with a std::list):

template <class Iter>
Iter previous(Iter it)
{
    return --it;
}

And then:

std::list<X>::iterator last = previous(li.end());

BTW, this might also be available in the boost library (next and prior).

UncleBens
This is available in C++0x as well (`std::next` and `std::prev`).
James McNellis