I am trying to remove some items from a string list in c++. The code compiles successfully but at runtime it gives "Segmentation fault (core dumped)" error. 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;
}