#include<iostream> #include <vector> int main() { std::vector<int> vec; vec.push_back(1); vec.push_back(2); vec.push_back(4); vec.push_back(4); vec.push_back(5); for (auto i = vec.begin(); i != vec.end(); ++i) { if (*i == 4) { vec.erase(i); } } getchar(); return 0; }
如果你这样试图删除为4的元素则达不到效果,因为erase后vec改变迭代器失效,但erase是返回下一个迭代器的
#include<iostream> #include <vector> int main() { std::vector<int> vec; vec.push_back(1); vec.push_back(2); vec.push_back(4); vec.push_back(4); vec.push_back(5); for (auto i = vec.begin(); i != vec.end();) { if (*i == 4) { i = vec.erase(i);//返回被删的下一个迭代器,可以利用这个特性 } else { i++; } } getchar(); return 0; }