C++ STL list 遍历删除出错解决方案

2025-05-27 0 15

C++ STL list 遍历删除崩溃

错误用法一

下面这种用法会在for的地方崩溃,分析 第一次for循环的时候 it=0,当t.erase(it)执行完成之后 it就变成了 -17891602
表明it不能再作为迭代器进行运算,自然会报错。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20
#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;

}

错误用法二

下面这种用法出现的错误与错误一相同

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19
#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;

}

错误用法三

下面这种用法以为不it++就不会有事,其实他们的错误都一样,那就是t.erase(it)之后 it已经是非迭代量,自然不能作为迭代操作

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21
#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;

}

正确用法

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19
#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;

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 C++ STL list 遍历删除出错解决方案 https://www.kuaiidc.com/74501.html

相关文章

发表评论
暂无评论