Search code examples
c++set-intersectionset-union

Trouble with set_union and set_intersection - C++


I am currently working on a project involving set calculations. I am using the functions set_union and set_intersection to calculate the union and intersection of sets. My variables are:

    int AunionB[8];
    int AunionC[7];                     // define AunionC
    int BunionD[9];                     // define BunionD
    int AintersectB[4];                 // define AintersectB
    int AintersectC[3];                 // define AintersectC
    set<int> finalUnion;                // final union of A, B, C, D
    set<int> finalIntersection;         // final intersection of A, B, C, D

These are the unions and intersections, respectively, of four sets: setA, setB, setC, and setD. My set_union function is as follows:

    set_union(AunionC, AunionC+7, BunionD, BunionD+9, finalUnion.begin());

And my set_intersection function is as follows:

    set_intersection(AintersectB, AintersectB+4, AintersectC, 
        AintersectC+3, finalIntersection.begin());

When I compile, I get the error "Required from here", the meaning of which I am not sure of. Can someone please help me with this? I believe it is something to do with the set_union and set_intersection functions and their parameters, but I'm not sure.


Solution

  • Use instead

    #include <iterator>
    
    //...
    
    set_union( AunionC, AunionC+7, BunionD, BunionD+9, 
               std::inserter( finalUnion, finalUnion.begin() ) );
    

    and

    set_intersection(AintersectB, AintersectB+4, AintersectC, 
        AintersectC+3, std::inserter( finalIntersection,  finalIntersection.begin() ) );
    

    A demonstrative example

    #include <iostream>
    #include <algorithm>
    #include <iterator>
    #include <set>
    
    
    int main()
    {
        int a[] = { 1, 3, 5 };
        int b[] = { 0, 2, 4, 6 };
        std::set<int> s;
    
        std::set_union( std::begin( a ), std::end( a ),
                        std::begin( b ), std::end( b ),
                        std::inserter( s, s.begin() ) );
    
        for ( int x : s ) std::cout << x << ' ';                 
        std::cout << std::endl;
        return 0;
    }
    

    The output is

    0 1 2 3 4 5 6