I'm getting segfault errors when I use the erase()
method in a class vector
container.
I'm comparing two vectors and, so I want to remove from one of them the elements that are not present in the another. To do so, I'm using iterators and erase()
as follow:
#include <vector>
int main () {
std::vector<int> vector1 {6,7,5,44,3,10,9,17,1};
std::vector<int> vector2 {1,2,3,5,8};
for (std::vector<int>::iterator it (vector2.begin()); it != vector2.end(); ++it) {
bool equal (false);
for (std::vector<int>::iterator jt (vector1.begin()); jt != vector1.end(); ++jt) {
if (*it == *jt) {
equal = true;
break ;
}
}
if (!equal) {
vector2.erase(it);
}
}
return 0;
}
What is causing the segfault is the deletion of the last element in vector2
(8
), because erase()
cannot succesfully move the iterator from the previous end()
position (no longer existant) to a new one.
How can this be prevented? I'm aware that unordered_set
could be a proper container for this operation, but here I'm interested in vector
.