Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator to last element in std::list

Tags:

c++

stl

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

like image 255
cpx Avatar asked Apr 20 '10 19:04

cpx


People also ask

How do I get the iterator to the last element in a list?

The list::end() is a built-in function in C++ STL which is used to get an iterator to past the last element. By past the last element it is meant that the iterator returned by the end() function return an iterator to an element which follows the last element in the list container.

What does list end () point to?

list::end() is an inbuilt function in C++ STL which is declared in <list> header file. end() returns the iterator which is referred to the element next to the end position in the list container. This function doesn't point to any element in the container.


1 Answers

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; 
like image 153
CB Bailey Avatar answered Oct 10 '22 20:10

CB Bailey