简体   繁体   English

如何从迭代器获取列表

[英]How to get a list from an iterator

How can I get a list from an iterator ? 如何从迭代器获取列表?

std::list<int> list;
auto it1 = list.insert(list.end(), 1);
auto it2 = list.insert(list.end(), 2);
auto it3 = list.insert(list.end(), 3);
auto it4 = list.insert(list.end(), 4);
auto it5 = list.insert(list.end(), 5);

list.erase(it3);

In included code, I am able to erase it3 from the list. 在包含的代码,我无法抹去it3从列表中。 What if I know only an iterator, can an iterator erase itself from the list without having the list variable ? 如果我只知道一个迭代器,迭代器可以在没有list变量的情况下从列表中擦除自身吗?

//Something like that
it2.list.erase(it2);

Technically it is possible to erase element in Doubly linked list and update neighboring nodes links after erasure. 从技术上讲,可以擦除双链表中的元素,并在擦除后更新相邻节点的链接。 But std::list also maintains it's size() , which must run in O(1) since C++11. 但是std::list也保持它的size() ,从C ++ 11开始必须在O(1)中运行。 So it is impossible to update the list size without accessing list itself. 因此,如果不访问列表本身就无法更新列表大小。

文档 std::list::iterator满足BidirectionalIterator概念,因此您可以看到,这两个概念都不是,它的祖先具有获取其所属容器的功能。

You can't get the list from an iterator, you can obtain the iterator from the list. 您不能从迭代器获取列表,而可以从列表获取迭代器。 The std::list container has an erase member function, iterator does not, so no, it can not erase itself. std :: list容器具有擦除成员功能,迭代器没有,因此不,它不能擦除自身。 If you know the iterator, supply it to the list's erase function. 如果您知道迭代器,则将其提供给列表的erase功能。 As pointed out in the comments you should not name your variable list , especially if you have using namespace std; 正如注释中指出的那样,您不应命名变量list ,尤其是在using namespace std; statement somewhere in your code which is also to be avoided. 语句在您的代码中的某处,也应避免。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM