#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貢獻(xiàn)1793條經(jīng)驗(yàn) 獲得超6個(gè)贊
貌似不是因?yàn)榈诙蝒rase有錯(cuò),而是,id等于3的時(shí)候erase完了就到vector的尾部了,erase操作成功返回值為當(dāng)前erase對(duì)象的next對(duì)象指針,需做判斷,然后跳出循環(huán)。
- 1 回答
- 0 關(guān)注
- 164 瀏覽
添加回答
舉報(bào)
0/150
提交
取消