Reputation: 879
I am new to cpp, and have a piece of code to run:
void particleFilter::mergeFilters(double mergeBound){
for(map<int, filter>::iterator fi = filters.begin(); fi != filters.end();){
for(map<int, filter>::iterator ji = filters.begin(); ji != filters.end(); ){
Rect recI = (fi -> second).getRecFilter();
Rect recJ = (ji -> second).getRecFilter();
double dis = (double)sqrt((double)(recI.x-recJ.x)*(recI.x-recJ.x)+(double)(recI.y-recJ.y)*(recI.y-recJ.y));
if(dis<mergeBound && dis>1){
double wi = (fi -> second).pi;
double wj = (ji -> second).pi;
cout <<"call remove function" << endl;
if(wi<wj){
cout << "remove id is " << (fi->second).objectID << endl;
removeFilter((fi->second).objectID);
fi++;
}
else{
cout << "remove id is " << (ji->second).objectID << endl;
removeFilter((ji->second).objectID);
ji++;
}
}
else{
++ji;
}
}
++fi;
}
}
It just has two pointers to compare every two entries of the map, but meanwhile, it deletes some entries of the map. There is nothing wrong with in the removeFilter((fi->second).objectID);
function for sure.
Anybody has any idea, why segmentation fault?
Upvotes: 0
Views: 73
Reputation: 198
You seem to increment fi
in the inner loop without checking if fi != filters.end()
Upvotes: 1
Reputation: 831
You can not remove a filter which is controlled by fi or ji and after that try to use this variables (for example, as ++fi ++ji)
Upvotes: 1
Reputation: 10316
You need to change this code:
removeFilter((fi->second).objectID);
fi++;
to something like:
auto tmpIt = fi;
fi++;
removeFilter((tmpIt->second).objectID);
And make a similar change to the equivalent ji
code also.
This is because the iterator which is erased is invalidated even though no other iterators to the container are. You are thus modifying an invalidated iterator, which is undefined behaviour. Making a copy and incrementing it first solves the problem.
Upvotes: 3