[積累]正確刪除Vector元素的方式

錯誤的刪除方法:
for(vector<int>::iterator it = vecInt.begin(); it != vecInt.end();it++)
{
       if( 1)//條件成立
        {
             vecInt.erase( it ); 
        }
}
使用上面的方法刪除元素,程序中會報錯:vector iterators incompatible,原因是erase後,it的指向是不定的,不能在用來跟vecInt中的元素做比較,正確的做法是將erase的返回值賦給變量it,erase函數的返回值是指向被刪除元素的後繼元素或者end.
正確的刪除方法:
for(vector<int>::iterator it = vecInt.begin(); it != vecInt.end();)
{
       if( 1)//條件成立
        {
             it = vecInt.erase( it ); 
        }else
        {
             it ++;
         }
}
發佈了400 篇原創文章 · 獲贊 14 · 訪問量 86萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章