国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > C++ > 正文

C++ STL list 遍歷刪除出錯(cuò)解決方案

2020-05-23 13:58:28
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

C++ STL list 遍歷刪除崩潰

錯(cuò)誤用法一

下面這種用法會(huì)在for的地方崩潰,分析 第一次for循環(huán)的時(shí)候 it=0,當(dāng)t.erase(it)執(zhí)行完成之后 it就變成了 -17891602
表明it不能再作為迭代器進(jìn)行運(yùn)算,自然會(huì)報(bào)錯(cuò)。

#include <map> #include <list> using namespace std; typedef std::list<int > TESTLIST; int _tmain(int argc, _TCHAR* argv[]) {   TESTLIST t;   for (int i = 0; i < 10;i++)   {     t.push_back(i);   }    for (TESTLIST::iterator it = t.begin(); it != t.end();)   {     t.erase(it);     it++;   }    return 0; } 

錯(cuò)誤用法二

下面這種用法出現(xiàn)的錯(cuò)誤與錯(cuò)誤一相同

#include <map> #include <list> using namespace std; typedef std::list<int > TESTLIST; int _tmain(int argc, _TCHAR* argv[]) {   TESTLIST t;   for (int i = 0; i < 10;i++)   {     t.push_back(i);   }    for (TESTLIST::iterator it = t.begin(); it != t.end();it++)   {     t.erase(it);   }    return 0; } 

錯(cuò)誤用法三

下面這種用法以為不it++就不會(huì)有事,其實(shí)他們的錯(cuò)誤都一樣,那就是t.erase(it)之后 it已經(jīng)是非迭代量,自然不能作為迭代操作

#include "stdafx.h"  #include <map> #include <list> using namespace std; typedef std::list<int > TESTLIST; int _tmain(int argc, _TCHAR* argv[]) {   TESTLIST t;   for (int i = 0; i < 10;i++)   {     t.push_back(i);   }    for (TESTLIST::iterator it = t.begin(); it != t.end();)   {     t.erase(it);   }    return 0; } 

 正確用法

#include <map> #include <list> using namespace std; typedef std::list<int > TESTLIST; int _tmain(int argc, _TCHAR* argv[]) {   TESTLIST t;   for (int i = 0; i < 10;i++)   {     t.push_back(i);   }    for (TESTLIST::iterator it = t.begin(); it != t.end();)   {     t.erase(it++);   }    return 0; } 

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 肇庆市| 马关县| 长葛市| 汽车| 柏乡县| 定州市| 龙岩市| 广汉市| 天台县| 新兴县| 封开县| 旺苍县| 百色市| 宝丰县| 子洲县| 阜新| 北京市| 卢龙县| 呼伦贝尔市| 沙河市| 皋兰县| 望江县| 沽源县| 德江县| 集安市| 九龙坡区| 双辽市| 金溪县| 右玉县| 泰兴市| 佛学| 平顺县| 盈江县| 红桥区| 右玉县| 博白县| 乌苏市| 娄烦县| 阿拉善右旗| 扬州市| 霍林郭勒市|