从 C++ 列表中删除项目

Sys*_*oft 4 c++ iterator list

我正在尝试从 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;
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 5

std::list<T,Allocator>::erase使已擦除元素的迭代器无效,即i。之后类似的操作i++通向UB。

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

while(i != entries.end())
{
    if(*i=="two")
        i = entries.erase(i);
    else
        i++;
}
Run Code Online (Sandbox Code Playgroud)