An iterator for the last item 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 iteration of the last item in a list?

+43
c ++ stl
Apr 20 '10 at 19:52
source share
7 answers

Yes, you can go back. (Assuming you know the list is not empty.)

 std::list<int>::iterator i = n.end(); --i; 
+75
Apr 20 '10 at 19:55
source share

Any of the following returns std::list<int>::iterator to the last element in 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()); 

Next, std::list<int>::reverse_iterator returns to the last element in list :

 std::list<int>::reverse_iterator iter = std::list::rbegin(); 
+42
Apr 20 '10 at 19:59
source share

Using reverse iterators:

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

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

+6
Apr 20 '10 at 20:15
source share

Take end() and go back.

 list <int>::iterator iter = n.end(); cout << *(--iter); 
+5
Apr 20 '10 at 19:58
source share
 std::list<int>::iterator iter = --n.end(); cout << *iter; 
+4
Jan 07 '13 at 6:11
source share

You can write your own functions to get the previous (and next) iterator from the given (which I used when I need to β€œlook” and β€œlook ahead” with std::list ):

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

And then:

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

BTW, this may also be available in the boost library ( hereinafter and earlier ).

+1
Apr 20 '10 at 20:20
source share
 list<int>n; list<int>::reverse_iterator it; int j; for(j=1,it=n.rbegin();j<2;j++,it++) cout<<*it; 
0
Nov 20
source share



All Articles