首页 > 解决方案 > 为什么会出现“来自不同容器的迭代器一起使用”CppCheck 错误?

问题描述

在我的代码中,我有 CppCheck 错误"Iterator 'it' from different container 'polyline' are used together"

你明白为什么它会出现在 please 的那一行.erase(it)吗?

for (QList<QPointF> &polyline : _polylinesPoints) {
        // Start loop with 2nd element and finish it before last element.
        for (auto it = polyline.begin() + 1; it < polyline.end() - 1;) {
            if (*it != newP1 && *it != newP2 && DesignUtils::areCollinear(*(it - 1), *it, *(it + 1)))
                it = polyline.erase(it); --> message here
            else
                ++it;
        }
    }

我的代码

我有一个基于 for 循环的迭代器的解决方案,但我想了解为什么在我测试它时我的代码似乎工作时会出现此错误。

我的解决方案是:

for (auto itPolyline = _polylinesPoints.begin(); itPolyline != _polylinesPoints.end(); ++itPolyline) {
        // Start loop with 2nd element and finish it before last element.
        for (auto it = itPolyline->begin() + 1; it < itPolyline->end() - 1;) {
            if (*it != newP1 && *it != newP2 && DesignUtils::areCollinear(*(it - 1), *it, *(it + 1)))
                it = itPolyline->erase(it);
            else
                ++it;
        }
    }

谢谢你的帮助。

巴蒂斯特

标签: c++iteratorcppcheck

解决方案


推荐阅读