c++中List在遍曆時刪除節點的方法,帶源碼

來源:互聯網
上載者:User

今天在開發的過程中遇到問題,想要遍曆一個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);}}


 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.