摘要:本文主要向大家介绍了C++语言中如何使用vector结合迭代器实现增删操作,通过具体的代码向大家展示,希望对大家学习C++语言有所帮助。
本文主要向大家介绍了C++语言中如何使用vector结合迭代器实现增删操作,通过具体的代码向大家展示,希望对大家学习C++语言有所帮助。
1 说明:目的是为了将vector里 符合isdel==true的元素删掉。
2 实现代码
[cpp] view plain copy 1. #include "stdafx.h" 2. #include <assert.h> 3. #include <time.h> 4. #include <ObjectArray.h> 5. 6. using namespace std; 7. 8. class Test 9. { 10. public: 11. Test(bool isdel) 12. { 13. this->is_delete=isdel; 14. } 15. bool is_delete; 16. }; 17. 18. void print(vector <Test> &v) 19. { 20. std::vector<Test >::iterator iter; 21. for(iter=v.begin();iter!=v.end();++iter) 22. { 23. cout<<(*iter).is_delete<<" "; 24. assert(!(*iter).is_delete); 25. } 26. cout<<endl; 27. } 28. 29. void add(vector <Test> &v,bool b) 30. { 31. Test *t= new Test(b); 32. v.push_back(*t); 33. delete t; 34. cout<<endl; 35. } 36. 37. void vec_del(vector <Test> &v) 38. { 39. std::vector<Test >::iterator iter; 40. for(iter=v.begin();iter!=v.end();) 41. { 42. if((*iter).is_delete==true) 43. { 44. iter=v.erase(iter); 45. } 46. else 47. { 48. ++iter; 49. } 50. } 51. } 52. 53. int _tmain(int argc, _TCHAR* argv[]) 54. { 55. vector <Test > svec; 56. std::vector<Test >::iterator iter; 57. srand(time(NULL)); 58. 59. cout<<"随机赋值:"<<endl; 60. 61. for(int i=0;i<100;++i) 62. { 63. int value=rand()%2; 64. add(svec,value); 65. 66. cout<<"i="<<i<<" T/F: "<<svec.at(i).is_delete<<endl; 67. } 68. cout<<endl<<"删除 true:"<<endl; 69. vec_del(svec); 70. print(svec); 71. cout<<endl; 72. 73. system("pause"); 74. return 0; 75. }
本文由职坐标整理并发布,了解更多内容,请关注职坐标编程语言C/C+频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号