vector中删除元素并且迭代器不失效

在一年前刚开始接触容器的时候经常写一些错误的代码,比如

#include <iostream>
#include <vector>
using namespace std;

int main()
{
	vector<int> vc = { 1,2,3,4,5,6,7,8,9 };
	int i = 0;
	for (auto it = vc.begin(); it != vc.end(); ++it)
	{
		if (*it == 6 || *it == 2 || *it == 3)
		{
			vc.erase(it);
		}
	}
	for (auto& aa : vc) cout << aa << " ";
 	return 0;
}

这样会使迭代器失效,然后继续访问就会出现未定义行为,进而产生错误。
昨天看到网上有人提出了这个问题,怎么删除容器的一个元素,并且迭代器不会失效,我想到了如下的方法。

#include <iostream>
#include <vector>
using namespace std;

int main()
{
	vector<int> vc = { 1,2,3,4,5,6,7,8,9 };
	int i = 1;
	for (auto it = vc.begin(); it != vc.end(); ++it)
	{
		if (*it == 6 || *it == 2 || *it == 3)
		{
			swap(*it, *(vc.end() - 1));
			--it;
			vc.resize(vc.size() - 1);
		}
	}
	for (auto& aa : vc) cout << aa << " ";
 	return 0;
}

我要删除6,2,3这三个元素,那么我将要删除的元素和最后一个元素的值调换一下,并且删除最后一个迭代器的值,这样就可以达到效果了。
在这里插入图片描述

结果也很对,但是有一个问题,我移到最后的元素始终占着内存,这样会使一些不必要的内存被占用。然后我又想到了另一个解决方法。

#include <iostream>
#include <vector>
using namespace std;

int main()
{
	vector<int> vc = { 1,2,3,4,5,6,7,8,9 };
	int i = 1;
	for (auto it = vc.begin(); it != vc.end(); ++it)
	{
		if (*it == 6 || *it == 2 || *it == 3)
		{
			swap(*it, *(vc.end() - 1));
			--it;
			vc.erase(vc.end() - 1);
		}
	}
	for (auto& aa : vc) cout << aa << " ";
 	return 0;
}

我把resize函数换成了erase函数就解决这个问题了,erase会使它之后的迭代器失效,那我后面没用元素了就随便它失效,无所谓。

这就是解决方案了 ,可能不是很好,希望各位大神指点出来,让我这个萌新学到更多的知识。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值