1

I have this code I made up to explain my problem:

#include <iostream>
#include <vector>

void
PrintVector (const std::vector<int> & vec)
{
  std::cout << "vector contains:";
  for (unsigned i = 0; i < vec.size (); ++i)
    std::cout << ' ' << vec[i];
  std::cout << '\n';
}

int
main ()
{
  std::vector<int> myvector;

  for (int i = 0; i <= 10; i++) myvector.push_back (i);
  PrintVector (myvector);

  int to_delete = 9;

  for (std::vector<int>::iterator it = myvector.begin (); it != myvector.end (); ++it)
    {
      if (*it == to_delete)
        {
          std::cout << *it << " found and deleted! \n";
          myvector.erase (it);
        }
    }
  PrintVector (myvector);

  to_delete = 10;

  for (std::vector<int>::iterator it = myvector.begin (); it != myvector.end (); ++it)
    {
      if (*it == to_delete)
        {
          std::cout << *it << " found and deleted! \n";
          myvector.erase (it);
        }
    }
  PrintVector (myvector);

  return 0;
}

I have a vector and I require to delete some elements. I don't know their position, so I have to iterate through the entire vector to look for them. I noticed that if the deleted element is the last position I get a Segmentation fault. I don't know why.

The output I get is:

vector contains: 0 1 2 3 4 5 6 7 8 9 10
9 found and deleted! 
vector contains: 0 1 2 3 4 5 6 7 8 10
10 found and deleted!         
10 found and deleted!       // QUESTION: This got repeated, why?

RUN FINISHED; Segmentation fault; core dumped; real time: 130ms; user: 0ms; system: 0ms

And it should be something like this:

vector contains: 0 1 2 3 4 5 6 7 8 9 10
9 found and deleted! 
vector contains: 0 1 2 3 4 5 6 7 8 10
10 found and deleted! 
vector contains: 0 1 2 3 4 5 6 7 8

RUN FINISHED; exit value 0; real time: 0ms; user: 0ms; system: 0ms
Steve B.
  • 73
  • 1
  • 5
  • This is a fairly common gotcha with C++ and iterators… watch out that you might end up with an invalid iterator. – Dietrich Epp Apr 22 '17 at 02:49
  • If you erase the last element, the iterator now points to `vector.end()`… so if you then `++` the iterator, you've gone *past* the end and get problems. – Dietrich Epp Apr 22 '17 at 02:50

0 Answers0