[算法] vector删除元素

红太狼 2022-06-06 08:48 316阅读 0赞
  1. #include <iostream>
  2. #include <algorithm>
  3. using namespace std;
  4. bool IsOdd (int i) { return i % 2 == 1; } // 奇数
  5. void test_remove(vector<int>& v)
  6. {
  7. auto del = remove(v.begin(), v.end(), 9); // 删除所有的9
  8. v.erase(del, v.end());
  9. //v.erase(del); // 错误的
  10. for(auto& it : v)
  11. cout << it << " "<< endl;
  12. }
  13. void test_remove_if(vector<int>& v)
  14. {
  15. auto del = remove_if(v.begin(), v.end(), IsOdd);
  16. v.erase(del, v.end()); // 删除所有奇数
  17. for(auto& it : v)
  18. cout << it << " "<< endl;
  19. }
  20. int main ()
  21. {
  22. vector<int> v = {1, 2, 3, 4, 6, 9, 10, 12, 9, 55};
  23. //test_remove(v);
  24. test_remove_if(v);
  25. return 0;
  26. }

从vector中删除元素,需要结合erase和remove或remove_if, 且得注意调用方式,否则会得到预料之外的结果!

发表评论

表情:
评论列表 (有 0 条评论,316人围观)

还没有评论,来说两句吧...

相关阅读