python/c++二重循环删除小于指定内容的点(迭代器bug)

工作中修改别人代码到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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值