简体   繁体   中英

C++set intersection and union using arrays

I've to find cardinality of set union and set intersection of two sets from a data file. I've created two arrays(setA[] and setB[]) to store my data. a and b are the number of elements in set A and set B respectively. setIntersection should hold the result of intersection between set A and B. But I'm stuck at how should I find the union and intersection.

int printIntersection(int setA[], int setB[], int setIntersection[], int a, int b, int k) 
{
 int i = 0;
 int j = 0;

 while(i < a && j < b)
 {
     if(setA[i] < setB[j])
     {
         i++;
     }

     else if(setA[i] > setB[j])
     {
         j++;
     }

     else if (setA[i] == setB[j])
     {
         setIntersection[k] = setA[i];
         i++;
         j++;
         k++;
     }
     cout<<"Cardinality of intersection is "<<k<<endl;
 }

This code is for intersection but I'm not getting anything. And I don't know where to start on union. can anyone help me out with the code thanks! PS I'm only allowed to use arrays and simple code algorithm. Thanks in advance!

Use std::set_union and std::set_intersection , eg

int *c = std::set_union(setA, setA + a, setB, setB + b, setC)
int *c = std::set_intersection(setA, setA + a, setB, setB + b, setC)

where setC is an output array of enough size; c points to one past the last element of the constructed range.

If you want cardinalities, c - setC is your answer.

I would recommend using something like std::vector for representation, and iterators instead of arrays/pointers/lengths in algorithm calls.

Input ranges are assumed sorted; so is the output.

If you want to do it yourself, you'll find "possible implementations" at the links above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM