【发布时间】:2020-11-18 08:29:14
【问题描述】:
从给定数组中删除给定元素时,我不断收到错误消息。
这是我的代码,我不确定错误在哪里:
int removeElement(vector<int>& nums, int val) {
int i=0;
int size=nums.size();
if(size <=0){
return 0;
}
for(int x : nums){
if(x==val){
nums.erase(nums.begin() + i );
}
i=i+1;
}
int size1=nums.size();
return size1;
}
然后我收到此错误:
=================================================================
==33==ERROR: AddressSanitizer: negative-size-param: (size=-8)
#8 0x7f3d479c882f (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
0x603000000060 is located 0 bytes to the right of 32-byte region [0x603000000040,0x603000000060)
allocated by thread T0 here:
#6 0x7f3d479c882f (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
==33==ABORTING
【问题讨论】:
-
在迭代向量时不能从向量中删除元素。它将使当前迭代器无效并导致未定义的行为。可能有重复的……某处。
标签: c++ arrays vector stl erase-remove-idiom