Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 way

like image 669
SNpn Avatar asked Oct 01 '11 02:10

SNpn


1 Answers

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;
    }
  }
like image 57
Greg Hewgill Avatar answered Oct 20 '22 00:10

Greg Hewgill