C++ Segmentation when using erase on std::list

青春壹個敷衍的年華 提交于 2019-12-04 04:07:43
JaredPar

The core problem here is you're using at iterator value, it, after you've called erase on it. The erase method invalidates the iterator and hence continuing to use it results in bad behavior. Instead you want to use the return of erase to get the next valid iterator after the erased value.

it = newList.begin();
for (int i = 0; i < 5; i++) {
  it = newList.erase(it);
}

It also doesn't hurt to include a check for newList.end() to account for the case where there aren't at least 5 elements in the list.

it = newList.begin();
for (int i = 0; i < 5 && it != newList.end(); i++) {
  it = newList.erase(it);
}

As Tim pointed out, here's a great reference for erase

When you erase an element at position it, the iterator it gets invalidated - it points to a piece of memory that you just freed.

The erase(it) function returns another iterator pointing to the next element to the list. Use that one!

You're invalidating your iterator when you erase() within the loop. It would be simpler to do something like this in place of your erase loop:

list_item_t::iterator endIter = newlist.begin();
std::advance(endIter, 5);
newList.erase(newlist.begin(), endIter);

You might also be interested in the erase-remove idiom.

I do this:

for(list<type>::iterator i = list.begin(); i != list.end(); i++)
{
     if(shouldErase)
     { 
        i = list.erase(i);
        i--;
     }
}

Edited because I'm a bonehead that can't read apparently lol.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!