标签:
1 #include <iostream> 2 #include <vector> 3 #include <string> 4 5 using namespace std; 6 7 int main(void) 8 { 9 vector<string> vecStr; 10 vecStr.push_back("aaa"); 11 vecStr.push_back("bbb"); 12 vecStr.push_back("ccc"); 13 vecStr.push_back("ddd"); 14 vecStr.push_back("eee"); 15 vecStr.push_back("fff"); 16 vecStr.push_back("ggg"); 17 18 for(vector<string>::iterator iter = vecStr.begin(); iter != vecStr.end(); ++iter) 19 { 20 cout << (*iter) << endl; 21 } 22 cout << "----------------------" << endl; 23 24 25 for(vector<string>::iterator iter = vecStr.begin(); iter != vecStr.end();) 26 { 27 cout << "execute item: " << (*iter) << endl; 28 if("ggg" == (*iter)) 29 { 30 cout << iter._Ptr << " " << *(iter._Ptr) << endl; 31 // 推荐方式 32 iter = vecStr.erase(iter); 33 cout << iter._Ptr << " " << *(iter._Ptr) << endl; 34 } 35 else 36 { 37 ++iter; 38 } 39 } 40 41 cout << "----------------------" << endl; 42 for(vector<string>::iterator iter = vecStr.begin(); iter != vecStr.end(); ++iter) 43 { 44 cout << (*iter) << endl; 45 } 46 47 }
所有项目
1 for(vector<string>::iterator iter = vecStr.begin(); iter != vecStr.end();) 2 { 3 cout << "execute item: " << (*iter) << endl; 4 cout << iter._Ptr << " " << *(iter._Ptr) << endl; 5 6 iter = vecStr.erase(iter); 7 8 cout << iter._Ptr << " " << *(iter._Ptr) << endl; 9 }
调用vector的erase方法后,之前的迭代器就失效了,必须赋予新的迭代器
标签:
原文地址:http://www.cnblogs.com/itpoorman/p/4434027.html