今天在開發的過程中遇到問題,想要遍曆一個List中的節點,滿足一定條件則刪除該節點,但是由於使用的是iterator就會出現錯誤,最後找到解決方案,並寫了一個測試程式,呵呵:
// ListTest.cpp : Defines the entry point for the console application.
//#include "stdafx.h"#include <iostream>#include <list>#include <algorithm>using namespace std;struct st_user{int id;char name[255];};int _tmain(int argc, _TCHAR* argv[]){st_user a1,a2,a3;a1.id = 1;sprintf(a1.name,"%s","xxxxxxxxx");a2.id = 2;sprintf(a2.name,"%s","fff");a3.id = 3;sprintf(a3.name,"%s","bbbb");list<st_user*> list1;list1.push_back(&a1);list1.push_back(&a2);list1.push_back(&a3);printf("------------------------------\n");for(list<st_user*>::iterator iter = list1.begin(); iter != list1.end(); ++iter){printf("%s \n", (*iter)->name);}printf("------------------------------\n");for(list<st_user*>::iterator iter = list1.begin(); iter != list1.end();){if( (*t)->id == 2 ){iter = list1.erase(t);}else++iter;}printf("------------------------------\n");for(list<st_user*>::iterator iter = list1.begin(); iter != list1.end(); ++iter){printf("%s \n", (*iter)->name);}printf("------------------------------\n");system("pause");return 0;}
運行結果:
--------------------------------------
@2015-7-20 10:06:01 修正了網友們提到的錯誤,哈哈,這個錯誤太低級了,敬請原諒
原來錯誤的代碼:
for(list<st_user*>::iterator iter = list1.begin(); iter != list1.end(); ++iter){if( (*t)->id == 2 ){list1.erase(t);}}