[英]std::list::erase does not invalidate other iterators and references
I read in cppreference that erase
does not affect iterators and references other than erased ones.我在 cppreference 中读到,
erase
不会影响迭代器和除擦除之外的引用。 But if I don't understand why following code does not work:但如果我不明白为什么以下代码不起作用:
#include <iostream>
#include <list>
int main()
{
std::list<int> lst;
lst.push_back(5);
lst.push_back(10);
lst.push_back(20);
int i = 0;
for (auto it = lst.begin(); it != lst.end(); ++it) // FIRST LOOP
{
if (i == 1) { lst.erase(it); }
++i;
}
for (auto el : lst) // SECOND LOOP
{
std::cout << el << std::endl;
}
return 0;
}
First loop never stops which causes Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
.第一个循环永远不会停止,这会导致
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
。 But I don't erase everything works fine.但我不会抹去一切正常。 So what is the problem?
那么问题是什么?
UPD: Tried to change UPD:试图改变
...
for (auto it = lst.begin(); it != lst.end(); ++it) // FIRST LOOP
...
to至
...
auto end = lst.end();
for (auto it = lst.begin(); it != end; ++it) // FIRST LOOP
...
but it did not help但这没有帮助
When you delete the element at it
, you cannot increment it
anymore.当您删除它的元素
it
,您不能再增加it
。 Therefore, you need to use this instead:因此,您需要改用它:
if (i == 1) { it = lst.erase(it); }
Also, you need to solve not to increment it
in this case.此外,您需要解决在这种情况下不要增加
it
。 So likely the increment would go inside the loop:增量很可能会进入循环内部:
int i = 0;
for (auto it = lst.begin(); it != lst.end(); ) // FIRST LOOP
{
if (i == 1)
{
it = lst.erase(it);
}
else
{
++it;
}
++i;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.