Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        4个月前关闭。
                                                                                            
                
        
我正在尝试找到两个向量的交集。我使用了两个循环,如果第一个循环元素等于第二个循环元素,则将该元素推入向量,然后删除该元素。但我一直收到错误“未处理的异常”。


#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

using namespace std;

void intersect(vector<int>& nums1, vector<int>& nums2)
{
    sort(nums1.begin(), nums1.end());
    sort(nums2.begin(), nums2.end());
    vector<int>v;
    if (nums1.size() > nums2.size())
    {
        for (int i = 0; i < nums1.size(); i++)
        {
            int first = nums1[i];
            for (int j = 0; j < nums2.size(); j++)
            {
                if (first == nums2[j])
                {
                    v.push_back(first);
                    nums2.erase(nums2.begin() + i);  //Getting an error here
                }
            }
        }
    }

    for (int i = 0; v.size(); i++)
        cout << v[i] << " ";
}

int main()
{
    vector<int>nums1 = { 1,2,2,1 };
    vector<int>nums2 = { 2,2 };
    intersect(nums1, nums2);
    return 0;
}

最佳答案

第一次调用会给您带来错误的代码时,i为2。由于nums2.begin()是第一个元素的迭代器,所以nums2.begin() + 2是第三个元素的迭代器。但是nums2没有第三个元素。因此,您尝试erase一个不存在的元素。

关于c++ - 从 vector 中删除元素时发生未处理的异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57471751/

10-13 06:27
查看更多