簡體   English   中英

C ++ Vector Iterator:比較和擦除兩個元素

[英]C++ Vector Iterator: Compare and Erase Two Elements

我有一個名為scene的std::vector<Shape*> ,它存儲指向Shapes的指針。 我需要能夠遍歷向量,將迭代器指向的形狀與迭代器中的下一個形狀進行比較。 如果s1->intersects(*s2)的返回為真,我需要從向量中刪除s1和s2。 以下代碼不正確,我得到一個異常vector interator is not incrementable

我怎么解決這個問題?

while (scene.size() > 1)
{
    for (std::vector<Shape*>::iterator it = scene.begin(); it != scene.end() - 1; it++)
    {
        Shape* s1 = (*it);
        Shape* s2 = (*(it + 1));

        if (s1->intersects(*s2))
        {
            delete s1;
            delete s2;

            // Remove the pointers to s1 and s2 from the vector.
            it = scene.erase(it);
            it = scene.erase(it);
        }
    }
}

看看代碼如何假定向量中沒有空指針,您可以使用空指針作為刪除標記,通過將標記與擦除分開來大大簡化邏輯。

for (std::vector<Shape*>::iterator it = scene.begin(); it < scene.end() - 1; ++it)
{
    Shape*& s1 = (*it);
    Shape*& s2 = (*(it + 1));
    if (s1->intersects(*s2))
    {
        delete s1;
        delete s2;
        s1 = NULL;
        s2 = NULL;
        ++it;
    }
}

scene.erase(std::remove(scene.begin(), scene.end(), NULL), scene.end());

it != scene.end() - 1 ,您的原始代碼可能已經通過更改it != scene.end() - 1來修復it != scene.end() - 1it < scene.end() - 1 因為如果最終刪除最后兩個元素,你將擁有一個等於scene.end()的迭代器,它滿足條件it != scene.end() - 1 ,並且循環將嘗試遞增它。

向量迭代器在擦除時變為無效。 你應該使用vector :: erase(iterator first,iterator last); 同時擦除矢量中的多個對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM