1
我想弄清楚如何使用remove_if
和vector<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
這是怎麼回事?