做一道求两数组交集的题目时我用迭代器遍历两个数组,并在迭代中用了erase操作,有了下面的报错
=================================================================
==42==ERROR: AddressSanitizer: negative-size-param: (size=-120)
#5 0x7f52c5b84082 (/lib/x86_64-linux-gnu/libc.so.6+0x24082)
0x602000000114 is located 4 bytes inside of 8-byte region [0x602000000110,0x602000000118)
allocated by thread T0 here:
#6 0x7f52c5b84082 (/lib/x86_64-linux-gnu/libc.so.6+0x24082)
==42==ABORTING
错误代码如下
for(vector<int>::iterator it1=nums1.begin();it1 !=nums1.end();)
{
for(vector<int>::iterator it2=nums2.begin();it2 !=nums2.end();)
{
if(*it1==*it2)
{
com.push_back(*it1);
nums1.erase(it1);
nums1.erase(it2);
continue;
}
it2++;
}
it1++;
}补充一点 可以利用迭代器修改vector元素
vector<int>v1;
v1.push_back(10);
vector<int>::iterator it = v1.begin();
*it = 12;
cout<<*it;v1先插入的元素10被修改为了12
在尝试计算两个整数数组的交集时,使用迭代器遍历并删除相同元素时出现了AddressSanitizer负大小参数错误。错误发生在尝试删除元素后继续迭代的过程中,可能由于删除操作导致迭代器失效。问题在于同时删除了`it1`和`it2`,而`it2`可能已因`it1`的删除变为无效。解决方案可能是只删除一个迭代器指向的元素,然后安全地移动另一个迭代器。
1122

被折叠的 条评论
为什么被折叠?



