0
点赞
收藏
分享

微信扫一扫

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


.

  • ​​c++标准规定可以直接传入一个key值进行删除​​
  • ​​erase 必须有一个真实的值,不能传递end​​
  • ​​如果想找到元素并且使用迭代器删除,需要进行判断​​

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

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


举报

相关推荐

0 条评论