Vector Sizes within For Loops

The following code compiles fine, but I think it's the source of my crashes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Method: fillConcavities
* Takes a polygon and fills all of the concave areas
*/
BWTA::Polygon ExampleAIModule::fillConcavities(BWTA::Polygon subject) {
	
	BWTA::Polygon result = subject;
	Position midPoint;
	int changes = 0;
	int between, second;

	// For each Vertex on the Current Polygon
	for(int i = 0; i < result.size(); i++) {

		if(i == result.size() - 2) {
			between = result.size() - 1;
			second = 0;
		} else if(i == result.size() - 1) {
			between = 0;
			second = 1;
		} else {
			between = i + 1;
			second = i + 2;
		}

		midPoint = Position((subject[i].x() + subject[second].x())/2, (subject[i].y() + subject[second].y())/2);

		// Draw a line from current vertex to the vertex 2 over and check if it
		// passes through the current polygon. If it doesn't, fill that area.
		if(subject.isInside(midPoint) == false) {
			result.erase(result.begin() + between);
			changes++;
		}
	}

	if(changes > 0) {
		return fillConcavities(result);
	} else {
		return result;
	}
}


A BWTA::Polygon is a vector of Positions. In this code i'm essentially taking a polygon, iterating through all of its vertexes, comparing each vertex with the vertex two spots further. If the line drawn between those vertexes is not inside the polygon being manipulated, I delete the vertex between them (filling the concave area). Each time a concave area is filled the changes is incremented. At the end of the method, if any changes were made, it recursively calls itself again.

I believe the issue lies within the fact that I use .erase() within the for loop, which utilizes the .size() of the vector. However, I tried to plan around that so it would still function.

Thanks for any help!
Topic archived. No new replies allowed.