map set erase(map.find(key)) 删除出错【必须判断迭代器是否有效】

C++标准库中安全删除元素的注意事项
本文讨论了C++中使用map或unordered_set删除元素时的常见问题。标准规定不能直接用end迭代器调用erase,而是应当先通过find方法查找元素,再进行删除。如果未找到key,直接使用find返回的迭代器删除会导致运行时异常。示例代码中展示了一个可能导致错误的删除操作,并指出了其潜在的bug寻找难度。

在这里插入图片描述

c++标准规定可以直接传入一个key值进行删除

https://stackoverflow.com/questions/952888/map-erase-map-end

erase 必须有一个真实的值,不能传递end

如果想找到元素并且使用迭代器删除,需要进行判断

erase(map.find(key))

这样是错误的,如果没有找到key 那么程序就会异常 而这个异常有时候会出现在其他的地方 很难定位

如下 ,在pos里面删除了unordered_set的end 在arr里面报错了

#include <iostream>
#include <set>
#include <vector>
#include <map>
#include <stack>
#include <tuple>
#include <algorithm>
#include <iterator>
#include <unordered_set>
#define debug(x) cout<<#x<<": "<<(x)<<endl;

using namespace std;

class pos {
public:
	int id = 0;
	unordered_set<int> s;
	pos() { s.rehash(1000); }
	//operator =
};

int getBoundByIncompatible() {

	int n = 600;
	vector<pos> arr(n);
	auto cmp = [&](const pos& a, const pos& b) {
		//return a.id<b.id;
		return a.s.size() < b.s.size();
	};

	for (int i = 1; i <= n; ++i) {
		for (int j = i + 1; j < n; ++j) {
			if (rand() % 3 == 0) {
				arr[i - 1].s.insert(j);
			}
		}
	}

	while (true) {

		debug(arr.size())
		sort(arr.begin(), arr.end(), cmp);

		bool isSucceed = true;
		int cus = -1;

		for (auto it = arr.begin(); it != arr.end(); ++it) {
			cus = it->id;
			arr.erase(it);
			break;
		}

		for (auto& node : arr) {
			if (node.s.find(cus) != node.s.end()) {
				node.s.erase(node.s.find(cus));
			}
		}
	}

}

int main() {
	
	getBoundByIncompatible();
	return 0;
}

窒息 找了很久bug

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值