开发者

segmentation fault when erasing an object from a vector c++

So I am seg faulting when I run this function

      class vector <Record<value> >::iterator itr = records.begin();

      for (; itr != records.end(); ++itr) {
        if (itr->isSelected()) {
          itr = records.erase(itr);
          recordSize--;
        }
      }

where my vector is of vector <Record <value> > records; and the function isSelected() is just a boolean that is either true when the object is selected or false when its not.

Can someone help me please, I don't see the problem with doing it this w开发者_开发知识库ay


In the case where you're deleting the last element, itr will first be records.end() because that's what records.erase() will return, and then you're incrementing it with ++itr. Try:

  while (itr != records.end()) {
    if (itr->isSelected()) {
      itr = records.erase(itr);
      recordSize--;
    } else {
      ++itr;
    }
  }


You shouldn't be erasing vector elements like that, it is not an efficient method as you may cause the reallocation of the vector several times during the process.

The correct and more efficient way of doing this is to use the std::erase function. See this question for examples.


for (; itr != records.end(); ++itr) is guaranteed not to escape the container and invoke UB if itr is not modified in the body of the loop, or if it is decremented.

Here you are advancing the iterator: itr = records.erase(itr);.

When you do so, no only you are skipping an element, also you may skip the one-past-the-end imaginary "element", IOW you may increment past one-past-the-end (UB).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜