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 w开发者_如何学JAVAay to have an iter to the last element in list?
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;
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();
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].
Take the end()
and go one backwards.
list <int>::iterator iter = n.end();
cout << *(--iter);
std::list<int>::iterator iter = --n.end();
cout << *iter;
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).
list<int>n;
list<int>::reverse_iterator it;
int j;
for(j=1,it=n.rbegin();j<2;j++,it++)
cout<<*it;
精彩评论