2013-10-28 30 views
1

刪除的對象的特定實例我有一個類圓形,其實例我一直與這些軌道:從矢量

Circle *f1; 
vector<Circle> list; 
vector<Circle>::iterator it; 

我已成功地創建多個圈子讓他們走動。我如何刪除Circle的特定實例?例如,如果某個圓圈碰到了一面牆,那麼它應該被刪除。我環顧了其他問題,甚至嘗試了他們發出的代碼,但沒有運氣。這是我現在得到的東西:

for (it = list.begin(); it != list.end(); ++it) { 

    it->x += 1; 

    if (it->x == ofGetWindowWidth()) { 
     list.erase(it); 
    } 
} 

我已經得到了其他語句與if語句一起工作,例如顛倒他們的運動方向。 list.erase(它);是我從這裏得到的一行代碼,我不明白爲什麼它會使我的程序崩潰。

回答

4
for (it = list.begin(); it != list.end(); /* nothing here */) { 

    it->x += 1; 

    if (it->x == ofGetWindowWidth()) { 
     it = list.erase(it); 
    } else { 
     ++it; 
    } 
} 

與原代碼的問題是,刪除元素無效的迭代該元素 - 你試圖旁邊增加非常相同的迭代器。這表現出未定義的行爲。

2

list.erase使迭代器無效到擦除元素。因此,擦除「it」指向的元素後,「it」將失效,並且在for循環體後跟隨的++可能會導致程序崩潰。 重寫你的代碼,類似的東西以下內容應防止你的崩潰:

for(it=list.begin();it!=list.end();) { 
    //your code 
    if(it->x==ofGetWindowWidth()) 
     it=list.erase(it); 
    else 
     ++it; 
} 
2

使用erase()上面代碼的問題是,當元素正在被擦除的it內容無效。您可以使用,例如,這個:荷蘭國際集團的元素

for (it = list.begin(); it != list.end();) { 
    it->x += 1; 

    if (it->x == ofGetWindowWidth()) { 
     list.erase(it++); 
    } 
    else { 
     ++it; 
    } 
} 

使用erase()移動保持迭代it關閉其當前位置的分支之前erase()。只有從it++返回的臨時對象纔會失效。當然,爲了使這個循環起作用,你不能無條件地增加it,即非分支需要它自己的增量。

0

你可以使用remove_if擦除。這也適用於刪除多個元素。在你的情況下,它

list.erase(std::remove_if(list.begin(), list.end(), 
     [](const Circle& c){return c.x == ofGetWindowWidth();},list.end()), 

例如用整數:

#include <algorithm> 
#include <vector> 
#include <iostream> 

int main() 
{ 
    std::vector<int> str1 = {1,3,5,7}; 
    str1.erase(std::remove_if(str1.begin(), str1.end(), 
           [](int x){return x<4 && x>2;}), str1.end()); 
    for(auto i : str1) std::cout << i ; 
} 

打印157