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("hello"); 11 vecStr.push_back("world"); 12 vecStr.push_back("welcome"); 13 vecStr.push_back("good"); 14 vecStr.push_back("boy"); 15 16 for(vector<string>::iterator iter = vecStr.begin(); iter != vecStr.end(); ++iter) 17 { 18 cout << (*iter) << endl; 19 } 20 cout << "----------------------" << endl; 21 22 for(vector<string>::iterator iter = vecStr.begin(); iter != vecStr.end(); ++iter) 23 { 24 cout << "execute item: " << (*iter) << endl; 25 if("welcome" == (*iter)) 26 { 27 // vector在删除元素后,返回迭代器指向下一个元素(windows STL和linux STL均支持) 28 iter = vecStr.erase(iter); 29 --iter; 30 } 31 } 32 cout << "----------------------" << endl; 33 for(vector<string>::iterator iter = vecStr.begin(); iter != vecStr.end(); ++iter) 34 { 35 cout << (*iter) << endl; 36 } 37 38 }
1 for(vector<string>::iterator iter = vecStr.begin(); iter != vecStr.end(); ++iter) 2 { 3 cout << "execute item: " << (*iter) << endl; 4 if("welcome" == (*iter)) 5 { 6 // window和linux均支持 7 vecStr.erase(iter--); 8 } 9 }
时间: 2024-10-16 12:45:19