工作中修改别人代码到c++进行效率加速的时候发现表现不一致:
- 二重循环删除某一个条件点的时候,单元测试总通不过,后来发现是迭代器的问题
1. 原理解析
2. c++处理代码
for(std::vector<POINT>::iterator i = intersections.begin(); i != intersections.end(); ++i){
for(std::vector<POINT>::iterator j = intersections.begin(); j != intersections.end(); ){
POINT point1 = *i, point2 = *j;
int p1_x = point1.first, p1_y = point1.second;
int p2_x = point2.first, p2_y = point2.second;
if ((pow(p1_x - p2_x, 2) + pow(p1_y - p2_y, 2)) < 100 && point1 != point2){
j = intersections.erase(j);
if (j < i){
--i;
}
}else{
++j;
}
}
}
3. python处理代码
i_len = len(intersections)
i = 0
while i < i_len:
point1 = intersections[i]
j = 0
while j < i_len:
point2 = intersections[j]
if (((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) < 10 ** 2) and (point1 != point2):
intersections.remove(point2)
i_len -= 1
if j < i:
i -= 1
else:
j += 1
i += 1