簡體   English   中英

使用算法擦除向量中的特定元素

[英]Erasing particular elements in a vector with algorithm

我想弄清楚remove_ifvector<T>::erase工作的。 我有下面的代碼(試圖刪除奇數元素):

v2.clear();
v2 = { 10, 20, 21, 30, 31, 33, 44, 66, 67 }; //vector<int>
cout << "v2 is now: " << endl;
printCollection(v2);    
cout << "Trying to remove odds from v2: " << endl;
auto what = remove_if(begin(v2), end(v2), [](int elem) {return elem % 2 != 0;});
v2.erase(begin(v2), what);
printCollection(v2);

這是輸出:

v2 is now:
10 20 21 30 31 33 44 66 67

Trying to remove odds from v2:
33 44 66 67

到底是怎么回事?

您的代碼行為未指定。 std::remove_if將所有未刪除的元素移動到容器的前面,並返回新的邏輯結束迭代器。 這種新的結束之間的所有元素( what在你的代碼)和.end()具有未定值。

您應該刪除what.end()代替:

v2.erase(what, end(v2));

演示

暫無
暫無

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

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