segmentation fault while erasing set

280 Views Asked by At

first, the following code produce a segmentatin fault and I dont know why.

    float currX;
    float currY;

    int id = 0;

    for(;it != s.end();){
        it_copy = it;
        pair<float,float> p = *it;
        currX = p.first;
        currY = p.second;

        currTresh = thresh;
        while(currTresh > 0 && it_copy != s.end()){
            pair<float,float> inner_p = *it_copy;
            currTresh--;
            if((inner_p.first-currX)<=secondThresh &&
                    abs(currY-inner_p.second)<=secondThresh){
                group.push_back(pair<int,KeyPoint>(id,KeyPoint(Point2f(p.first,p.second),9,-1,0,0,0)));
                s.erase(it_copy++);
            } else {
                ++it_copy;
            }
        }
        id++;
        it++;
    }

Here is the scenario: I try to group some Points. Points which are similar e.g. similar coordinates. For example P1(10,5) ; P2(11,6) ; p3(11,50) Group1(P1,P2) ; Group2(P3)

I will realize this as follows.

The use of set brings the advantage that duplicates are removed and the pairs of x and y coordinates are sorted.

The for-loop should iterate over the complete set s. Here the iterator 'it' is used. In a inner while-loop I will pick a amount of values of s, depend of the tresh. thresh and sencondThresh are 10! In the while-loop I set the condition that similar points are grouped. If a point insert in the group I will earase it from the set s. To avoid, that the same Point is in different groups. And this is the line, I think the segmentation fault comes from.

I hope you can help me.

1

There are 1 best solutions below

4
On

Your call to erase modifies s, invalidating it. So you can't increment it after that.

Perhaps you intended it = it_copy; rather than it++;?