在c++98标准中,std::set和std::list可采用如下方式:
/** * 仅适用于std::set */ #include <iostream> #include <set> int main() { std::set<int> test; for (int i = 0;i < 10; ++i) test.insert(i); std::set<int>::iterator it = test.begin(); while ( it != test.end()) { if ( *it == 2 || *it == 3) { test.erase(it++); } else it++; } return 0; }而std::vector和std::list可用如下方式:
/** * 适用于std::vector和std::list */ #include <iostream> #include <vector> int main() { std::vector<int> test; for (int i = 0;i < 10; ++i) test.push_back(i); std::vector<int>::iterator it = test.begin(); while ( it != test.end()) { if ( *it == 2 || *it == 3) { it = test.erase(it); } else it++; } return 0; }也就是说,std::set仅能用第一种遍历方式,std::vector只能用第二种,而std::list两种都可以。 在c++11标准中,以上接口已经做了统一,都可以采用下面这种方式。
