c++ - 寻找 2 个 vector 的交集算法评论/解释

标签 c++ arrays algorithm vector

我在 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 &lt 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;
    }
};
我想知道为什么我不能删除第二个数组中与第一个数组中的元素匹配的元素。

最佳答案

如果 nums2nums1 之前变为空确实,您的程序通过访问 nums2[0] 表现出未定义的行为.超出范围的索引。

关于c++ - 寻找 2 个 vector 的交集算法评论/解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63222271/

相关文章:

c++ - 有没有一种方法可以在不使用命名空间 std 或以 std::为前缀的情况下引用 cout?

c++ - 如何将纹理应用于 openscenegraph 中的模型?

c++ - 来自 void 的多态类型转换*

javascript - 在两个方向上迭代一个范围

python - 压缩一维 numpy 数组到二维汉明距离矩阵

arrays - 在内存有限的情况下找到数组中出现次数最多的数字

c++ - 在指向 POD 类型的指针之间静态转换与重新解释转换

java - Java 中的 For 循环和数组

arrays - 在 O(n) 时间内检查两个子串是否重叠

python - 如何生成列表的所有排列以及添加在任何排列中只能出现一次的字符串