[英]Removing items from c++ list
I am trying to remove some items from a string list in c++.我正在尝试从 c++ 中的字符串列表中删除一些项目。 The code compiles successfully but at runtime it gives " Segmentation fault (core dumped) " error.
代码编译成功,但在运行时会出现“ Segmentation fault (core dumped) ”错误。 I have abstracted the code as follows.
我将代码抽象如下。
#include <iostream>
#include <list>
using namespace std;
int main()
{
//a string list
list<string> entries;
//add some entries into the list
entries.push_back("one");
entries.push_back("two");
entries.push_back("three");
entries.push_back("four");
//pass over the list and delete a matched entry
list<string>::iterator i = entries.begin();
while(i != entries.end())
{
if(*i=="two")
entries.erase(i); // *** this line causes the error ***
i++;
}
//print the result
for(const string &entry : entries)
cout<<entry<<"\n";
return 0;
}
std::list<T,Allocator>::erase
invalidates the iterator to the erased element, ie i
.std::list<T,Allocator>::erase
使擦除元素的迭代器无效,即i
。 After that the operation like i++
leads to UB.之后像
i++
这样的操作导致 UB。
You can assign it to the return value of erase
, which is iterator following the removed element.您可以将其分配给
erase
的返回值,它是被删除元素之后的迭代器。
while(i != entries.end())
{
if(*i=="two")
i = entries.erase(i);
else
i++;
}
Erased iterators are invalidated.擦除的迭代器无效。 For your convenience,
list::erase
returns next past erased:为方便起见,
list::erase
返回下一个已删除的过去:
if(*i == "two") i = list.erase(i);
else ++i;
you can just "remove" the element, no need for iterators, but if you use it, then be aware that erase invalidates the iterator..您可以只“删除”元素,不需要迭代器,但是如果您使用它,请注意擦除会使迭代器无效。
#include <iostream>
#include <list>
int main ()
{
//a string list
std::list<std::string> entries;
//add some entries into the list
entries.push_back("one");
entries.push_back("two");
entries.push_back("three");
entries.push_back("four");
entries.push_back("two");
entries.remove("two");
std::cout<<entries.size() << std::endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.