#include "vector"#include "string"#include "iostream"using namespace std;struct STUDENT{public:int id;string name;STUDENT(int id, string name){this->id = id;this->name = name;}};vector<STUDENT> v;void display();void main(){STUDENT s1(1,"zhao");STUDENT s2(2,"sun");STUDENT s3(3,"li");v.push_back(s1);v.push_back(s2);v.push_back(s3);display();//第一次删除for(vector<STUDENT>::iterator itr1 = v.begin(); itr1 != v.end(); itr1++){if(itr1->id == 1){v.erase(itr1);}}cout<<"==================="<<endl;display();//第二次删除for(vector<STUDENT>::iterator itr2 = v.begin(); itr2 != v.end(); itr2++){if(itr2->id == 3){v.erase(itr2);}}cout<<"==================="<<endl;display();}void display(){for(vector<STUDENT>::iterator itr = v.begin(); itr != v.end(); itr++){cout<<itr->name<<endl;}}
1 回答
摇曳的蔷薇
TA贡献1793条经验 获得超6个赞
貌似不是因为第二次erase有错,而是,id等于3的时候erase完了就到vector的尾部了,erase操作成功返回值为当前erase对象的next对象指针,需做判断,然后跳出循环。
- 1 回答
- 0 关注
- 114 浏览
添加回答
举报
0/150
提交
取消