Iterator to last element in std::list
C++StlC++ Problem Overview
#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?
C++ Solutions
Solution 1 - C++
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 - C++
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 - C++
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].
Solution 4 - C++
Take the end()
and go one backwards.
list <int>::iterator iter = n.end();
cout << *(--iter);
Solution 5 - C++
std::list<int>::iterator iter = --n.end();
cout << *iter;
Solution 6 - C++
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).
Solution 7 - C++
list<int>n;
list<int>::reverse_iterator it;
int j;
for(j=1,it=n.rbegin();j<2;j++,it++)
cout<<*it;