C++ std::list 中最后一个元素的迭代器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2678175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterator to last element in std::list
提问by cpx
#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?
有没有其他方法可以对列表中的最后一个元素进行迭代?
回答by CB Bailey
Yes, you can go one back from the end. (Assuming that you knowthat the list isn't empty.)
是的,你可以从最后返回一个。(假设您知道该列表不为空。)
std::list<int>::iterator i = n.end();
--i;
回答by Remy Lebeau
Either of the following will return a std::list<int>::iterator
to the last item in the list
:
以下任一项将返回 astd::list<int>::iterator
到 中的最后一项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
:
以下将返回 astd::list<int>::reverse_iterator
到 中的最后一项list
:
std::list<int>::reverse_iterator iter = std::list::rbegin();
回答by Eugen Constantin Dinca
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].
作为旁注:this 或 Charles Bailey 方法具有恒定的复杂性,而std::advance(iter, n.size() - 1);
与列表具有线性复杂性 [因为它具有双向迭代器]。
回答by Mitten.O
Take the end()
and go one backwards.
拿走end()
一个倒退。
list <int>::iterator iter = n.end();
cout << *(--iter);
回答by Meysam
std::list<int>::iterator iter = --n.end();
cout << *iter;
回答by UncleBens
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
):
您可以编写自己的函数来从给定的迭代器中获取上一个(和下一个)迭代器(当我需要使用 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).
顺便说一句,这也可能在 boost 库(next 和 previous)中可用。
回答by Alexandru Manescu
list<int>n;
list<int>::reverse_iterator it;
int j;
for(j=1,it=n.rbegin();j<2;j++,it++)
cout<<*it;