做一道求两数组交集的题目时我用迭代器遍历两个数组,并在迭代中用了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