我试图从C++字符串列表中删除一些项目。代码编译成功,但在运行时出现“分段错误(core dumped)”错误。我已经将代码抽象如下。
#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;
}
i
时会发生什么。在那之后,迭代器是否真的有效?我推荐使用此erase
参考,请注意它返回什么。 - Some programmer dudeerase
returns the iterator. Doif() { i=erase} else {i++}
- manuell