c++第五版练习9.26
练习9.26 使用下面代码定义的ia,将ia拷贝到一个vector和一个list中,使用单迭代器版本的erase从list中删除奇数元素,从vector中删除偶数元素
1 #include <iostream> 2 #include <list> 3 #include<vector> 4 using namespace std; 5 6 vector<int> DeleteVect(vector<int> & veca) //引用 7 { 8 auto it = veca.begin(); 9 while (it != veca.end()) 10 if (*it%2==0) 11 it = veca.erase(it); //删除其中的偶数 12 else 13 ++it; 14 return veca; 15 } 16 17 list<int> DeleteList(list<int> & veca) //引用 18 { 19 auto it = veca.begin(); 20 while (it != veca.end()) 21 if (*it % 2 == 1) 22 it = veca.erase(it); //删除其中的奇数 23 else 24 ++it; 25 return veca; 26 } 27 28 int main() 29 { 30 int ia[] = {0,1,1,2,3,5,8,13,21,55,89}; 31 vector<int>vec; 32 list<int>lst; 33 vec.assign(&ia[0],&ia[11]); //将ia[]拷贝到vector容器中 34 lst.assign(&ia[0], &ia[11]); //将ia[]拷贝到vector容器中 35 36 cout << "Please printf the odd number:" << endl; 37 DeleteVect(vec); 38 for (auto it : vec) 39 { 40 cout << it << endl; 41 } 42 43 cout << "Please printf the even number:" << endl; 44 DeleteList(lst); 45 for (auto it : lst) 46 { 47 cout << it << endl; 48 } 49 getchar(); 50 return 0; 51 }