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