我在 cpp 中有 2 个 vector :[1,2,2,1] 和 [2,2]。我希望交叉点是:[2,2]。这是我实现的算法,但我得到了堆溢出,我不知道为什么。有人可以向我解释发生了什么问题吗?
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
//This is the intersection we will return
vector<int> out;
//If either array's are empty the intersection is empty
if(nums1.size() == 0 || nums2.size() == 0) return out;
//Iterate through first array, then go through each element of second array. After the end of each iteration we pop_front of first array. (Change to while loop)
for(int i = 0; i < nums1.size(); nums1.erase(nums1.begin())){
//flag to break out of second array iteration
bool flag = false;
int j = 0;
while (!flag){
if(nums1[i] == nums2[j]){
//Append the answer to the output. Doesn't matter if it is from array 1 or 2 they are equal
out.push_back(nums1[i]);
//I want to erase the element in the second array that was matched in the first array to insure that no integer is matched in the next iteration of the first array. (Heap buffer overflow??)
nums2.erase(nums2.begin()+j);
//If a match was found we break out of the second array iteration
flag = true;
}
//Check if index j is out of bounds, if it is we have reached the end of the second array
if(j == nums2.size() - 1){
flag = true;
}
j++;
}
}
return out;
}
};
我想知道为什么我不能删除第二个数组中与第一个数组中的元素匹配的元素。
最佳答案
如果 nums2
在 nums1
之前变为空确实,您的程序通过访问 nums2[0]
表现出未定义的行为.超出范围的索引。
关于c++ - 寻找 2 个 vector 的交集算法评论/解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63222271/