[算法] vector删除元素
生活随笔
收集整理的這篇文章主要介紹了
[算法] vector删除元素
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include <iostream>
#include <algorithm>using namespace std;bool IsOdd (int i) { return i % 2 == 1; } // 奇數void test_remove(vector<int>& v)
{auto del = remove(v.begin(), v.end(), 9); // 刪除所有的9v.erase(del, v.end());//v.erase(del); // 錯誤的for(auto& it : v)cout << it << " "<< endl;
}void test_remove_if(vector<int>& v)
{auto del = remove_if(v.begin(), v.end(), IsOdd);v.erase(del, v.end()); // 刪除所有奇數for(auto& it : v)cout << it << " "<< endl;
}int main ()
{vector<int> v = {1, 2, 3, 4, 6, 9, 10, 12, 9, 55};//test_remove(v);test_remove_if(v);return 0;
}
從vector中刪除元素,需要結合erase和remove或remove_if, 且得注意調用方式,否則會得到預料之外的結果!
總結
以上是生活随笔為你收集整理的[算法] vector删除元素的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java 网络编程1
- 下一篇: JVM 类型的生命周期学习