从 c++ 列表中删除项

Removing items from c++ list

本文关键字:删除 列表 c++      更新时间:2023-10-16

我正在尝试从 c++ 的字符串列表中删除一些项目。代码编译成功,但在运行时出现">分段错误(核心转储("错误。我将代码抽象如下。

#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

使迭代器无效到被擦除的元素,即i.之后,像i++这样的操作会导致 UB。

您可以将其分配给erase的返回值,该值是删除元素之后的迭代器。

while(i != entries.end())
{
if(*i=="two")
i = entries.erase(i);
else
i++;
}

擦除的迭代器将失效。为方便起见,list::erase返回的下一个删除的过去:

if(*i == "two") i = list.erase(i);
else ++i;

你可以"删除"元素,不需要迭代器,但如果你使用它,那么请注意擦除会使迭代器无效。

#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;
}