Segmentation error when deleting an object from a C ++ vector

So, I execute this function while executing 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 matters vector <Record <value> > records;, and the function isSelected()is simple boolean, which is either true when the object is selected, or false when it is not.

Can someone help me please, I don't see a problem with this like that.

+5
source share
3 answers

In the case when you delete the last item, it itrwill first records.end(), because that will return records.erase(), and then increase it by ++itr. Try:

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

, , , .

- std:: erase. . .

+1

for (; itr != records.end(); ++itr)guaranteed to not exit the container and call UB if it itrdoes not change in the body of the loop or if it is reduced.

Here you are promoting an iterator: itr = records.erase(itr);.

When you do this, you simply skip the element, you can also skip the "imaginary" element "one end of the past", IOW, which you can increase in one pass to the end (UB).

+1
source

All Articles