Search code examples
c++setdifference

C++ Union , Intersection , Difference


So I'm working on a code to find the Union, Intersection and Difference between two arrays. I'm done with the Union and Intersection but i just can't figure out the difference(A - B) ,For example A={1,3,6,9,7,9} , B={2,3,-2,9} i want to get A - B = { 1,6,7,0} .

I don't want to use any other library except iostream.

This is my code so far.

/* Prints union of A[] and B[]
   SizeA is the number of elements in A[]
   SizeB is the number of elements in B[] */

cout << "\nUnion of A and B = "; //
i = 0; j = 0;
while (i < SizeA && j < SizeB)
{
    if (A[i] < B[j])
        cout << A[i++] << " ";

    else if (B[j] < A[i])
        cout << B[j++] << " ";

    else
    {
        cout << B[j++] << " ";
        i++;
    }
}
/* Print remaining elements of the larger array */
while (i < SizeA)
    cout << A[i++] << " ";

while (j < SizeB)
    cout << B[j++] << " ";



cout << "\nIntersection of A and B = ";
for (i = 0; i < SizeA; i++) //for loop to calculate the intersection of A and B.
{
    for (j = 0; j < SizeB; j++)
    {
        if (A[i] == B[j])
        {
            cout << A[i] << " ";
        }
    }
}

Solution

  • This is very bad practice because it's not general, not using a clean function and using plain old arrays but I assumed that you are beginner and have to do it in this way

    #include <iostream>
    
    int main()
    {
        int A [] ={1,3,6,9,7}, Asz =  5, B [] ={2,3,-2,9}, Bsz =  4;
        std::cout << "\nThe difference is {";
        for( int i = 0; i < Asz; ++i){
            int temp = A[i];
            bool notFound = true;
            for(int j = 0; j < Bsz; ++j){
                if(temp == B[j]) notFound = false;
            }
            if(notFound)
            {
                if(i < Asz - 1) std::cout << temp << ", ";
                else std::cout << temp ;
            }
        }
        std::cout << "}";
    }
    

    The way I prefer

    #include <iostream>
    #include <vector>
    #include <algorithm>
    int main()
    {
        std::vector<int> A = {1,3,6,9,7, 0} , B={2,3,-2,9}, C;
    
        std::sort(A.begin(), A.end());
        std::sort(B.begin(), B.end());
    
        std::set_difference(A.cbegin(), A.cend(), B.cbegin(), B.cend(), std::back_inserter(C), std::less<int>{});
    
        for(auto const & el : C)
            std::cout << el << ", ";
    }