指向 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
}
还有其他方法可以迭代到列表中的最后一个元素吗?
#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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
是的,你可以从最后倒回去。 (假设您知道该列表不为空。)
Yes, you can go one back from the end. (Assuming that you know that the list isn't empty.)
以下任一操作都会将
std::list::iterator
返回到list
中的最后一项:以下代码将
std::list::reverse_iterator
返回到list
中的最后一项:Either of the following will return a
std::list<int>::iterator
to the last item in thelist
:The following will return a
std::list<int>::reverse_iterator
to the last item in thelist
:使用反向迭代器:
附带说明:此方法或 Charles Bailey 方法具有恒定的复杂性,而 std::advance(iter, n.size() - 1); 具有列表的线性复杂性 [因为它具有双向迭代器]。
With reverse iterators:
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].使用
end()
并向后退一步。Take the
end()
and go one backwards.您可以编写自己的函数来从给定的迭代器中获取上一个(和下一个)迭代器(当我需要使用
std::list< 进行“后视”和“前视”时,我使用了该迭代器) /code>):
然后:
顺便说一句,这也可能在 boost 库中可用 (
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
):And then:
BTW, this might also be available in the boost library (next and prior).