我做错了什么导致无限循环

时间:2014-01-17 15:01:13

标签: c++ for-loop iterator infinite-loop

所以我使用了一个向量列表,我的代码似乎打破了它,以便for循环不会退出。

这是有效的代码:

for(possible_planes_it = possible_planes.begin(); possible_planes_it != possible_planes_end; possible_planes_it++)
{
    if(static_cast<float>(good_matches.size()) >= static_cast<float>((matches.size())*0.8))
    {
        possible_planes_it->push_back(Plane(area, *center_it, keypoint, descriptor, count));
    }
    else
    {
        list.push_back(vector<Plane>());
        list.back().push_back(Plane(area, *center_it, keypoint, descriptor, count));
    }
}

这会导致迭代器中断:

for(possible_planes_it = possible_planes.begin(); possible_planes_it != possible_planes_end; possible_planes_it++)
{
        if(static_cast<float>(good_matches.size()) >= static_cast<float>((matches.size())*0.8))
        {
        if(possible_planes_it->back().getTimestamp() < count) // Means that there has not been a match found this round
        {
            possible_planes_it->push_back(Plane(area, *center_it, keypoint, descriptor, count));
            possible_planes_it->back().setNumberOfGoodMatches(good_matches.size());
        }
        else
        {
            if(possible_planes_it->back().getNumberOfGoodMatches() < good_matches.size())
            {
                possible_planes_it->pop_back(); // If a better match has been found, remove the last vector entry and push the new one
                possible_planes_it->push_back(Plane(area, *center_it, keypoint, descriptor, count));
                possible_planes_it->back().setNumberOfGoodMatches(good_matches.size());
            }
            else
            {
                list.push_back(vector<Plane>());
                list.back().push_back(Plane(area, *center_it, keypoint, descriptor, count));
            }
        }
    }
    else
    {
        list.push_back(vector<Plane>());
        list.back().push_back(Plane(area, *center_it, keypoint, descriptor, count));
    }
}

有没有人知道我做错了什么:D?

1 个答案:

答案 0 :(得分:1)

查看向量的pop_backpush_back页面,具体来说,请参阅迭代器有效性,并注意如果发生重定位,迭代器将如何失效。

另见What is iterator invalidation?