vector中erase的兩種常見錯誤

原文鏈接:https://segmentfault.com/a/1190000016096696

//在循環中使用erase需要避免的錯誤

//erase的函數原型有兩種形式:
//iterator erase(iterator position);
//iterator erase(iterator first, iterator last); 左閉右開 [first,last)

vector<int> v1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 9, 10, 9 };

錯誤示例1

for (auto p1 = v1.begin(); p1 != v1.end();p1++)
{
    if (*p1 == 9)
    {
        v1.erase(p1);
    }
}

//p1被erase以後,變成了一個“野迭代器”,對其進行++操作會發生未定義的錯誤

Return value
An iterator pointing to the new location of the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.

會返回指向刪掉的元素後面第一個元素的迭代器,如果刪掉的是最後一個元素,返回end()

錯誤示例2

for (auto p1 = v1.begin(); p1 != v1.end();p1++)
{
    if (*p1 == 9)
    {
        p1=v1.erase(p1);
    }
}

1)無法刪除兩個連續的9: 由於erase會返回指向下一個元素的迭代器,因此會跳過一個元素
2)當9位於vector最後位置的時候,也會出錯,erase操作後p1指向end()(循環體第3個參數:在ve.end()上執行 ++ 操作會超過end(),無定義,報錯)

正確示例

for (auto p1 = v1.begin(); p1 != v1.end();)
{
    if (*p1 == 9)
    {
        p1=v1.erase(p1);
    }
    else
    {
        p1++;
    }
}

轉:https://segmentfault.com/a/1190000016096696

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章