迭代器遍历的时候删除元素

#include <vector>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

using namespace std;

int main(int argc, char* argv[])
{
	std::vector<int> test_vec;
	for(int i = 0 ;i < 10;i++)
		test_vec.push_back(i);
	
	for(std::vector<int>::iterator itor = test_vec.begin();itor!=test_vec.end();itor++)
	{
		printf("node = %d\n" ,*itor);
		
	}
	printf("node size = %d\n" ,test_vec.size());
	
    getchar();
    return 0;
}

输出如下:

node = 0
node = 1
node = 2
node = 3
node = 4
node = 5
node = 6
node = 7
node = 8
node = 9
node size = 10

现在我们要在迭代的时候进行删除其中某个元素

#include <vector>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

using namespace std;

int main(int argc, char* argv[])
{
	std::vector<int> test_vec;
	for(int i = 0 ;i < 10;i++)
		test_vec.push_back(i);
	
	for(std::vector<int>::iterator itor = test_vec.begin();itor!=test_vec.end();itor++)
	{
		printf("node = %d\n" ,*itor);
		if(*itor == 2)
		{
			test_vec.erase(itor);
		}
	
	}
	printf("node size = %d\n" ,test_vec.size());
	
    getchar();
    return 0;
}

输出如下:

node = 0
node = 1
node = 2
node = 4
node = 5
node = 6
node = 7
node = 8
node = 9
node size = 9

比较意外,3居然没遍历到????

接下来是正确的代码

#include <vector>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

using namespace std;

int main(int argc, char* argv[])
{
	std::vector<int> test_vec;
	for(int i = 0 ;i < 10;i++)
		test_vec.push_back(i);
	
	for(std::vector<int>::iterator itor = test_vec.begin();itor!=test_vec.end();)
	{
		printf("node = %d\n" ,*itor);
		if(*itor == 2)
		{
			itor =test_vec.erase(itor);
		}
		else
		{
			itor++;
		}
		
	}
	printf("node size = %d\n" ,test_vec.size());
	
    getchar();
    return 0;
}

输出:

node = 0
node = 1
node = 2
node = 3
node = 4
node = 5
node = 6
node = 7
node = 8
node = 9
node size = 9
使用vector的erase函数,记 住,该函数是迭代器失效,返回下一个迭代器
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值