Segmentation fault while calculating the intersection of two sets

Viewed 166

I need to find the intersection of two arrays and print out the number of elements in the intersection of the two arrays. I must also account for any duplicate elements in both the arrays. So, I decide to take care of the duplicate elements by converting the two arrays into sets and then take the intersection of both the sets. However, I encounter a segmentation fault when I run my code. I'm not sure where this occurs, any way to fix this?

#include<iostream>
#include<algorithm>
#include<vector>
#include<set>
using namespace std;
int NumberofElementsInIntersection (int a[], int b[], int n, int m ){
        // Your code goes here
        int i=0,j=0,count=0;
        set<int> s1,s2;
        vector<int> v;
        vector<int>::iterator it;
        for(i=0;i<n;i++)
            s1.insert(a[i]);
        for(i=0;i<m;i++)
            s2.insert(b[i]);
       it=set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end(),v.begin());
       return (it-v.begin());
}

int main(){
    int a[] = {1, 2, 3, 4, 5, 6};
    int b[] = {3, 4, 5, 6, 7};
    cout<<NumberofElementsInIntersection(a,b,6,5);
    return 0;
}
3 Answers

See https://en.cppreference.com/w/cpp/algorithm/set_intersection

Your vector iterator does not resize the vector to add new elements. You should have used a back_inserter instead.

//also needs #include <iterator>
int NumberofElementsInIntersection (int a[], int b[], int n, int m ){
        // Your code goes here
        int i=0;
        set<int> s1,s2;
        vector<int> v;
        for(i=0;i<n;i++)
            s1.insert(a[i]);
        for(i=0;i<m;i++)
            s2.insert(b[i]);
       set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end(),back_inserter(v));
       return v.size();
}
Related