简体   繁体   English

C ++使用数组设置交集和并集

[英]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. 我要找到set union的基数,并从数据文件中设置两组的交集。 I've created two arrays(setA[] and setB[]) to store my data. 我创建了两个数组(setA []和setB [])来存储我的数据。 a and b are the number of elements in set A and set B respectively. a和b分别是集合A和集合B中的元素数量。 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. setIntersection应该保存集合A和集合B之间的交集结果。但我仍然坚持如何找到并集和交集。

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. PS我只允许使用数组和简单的代码算法。 Thanks in advance! 提前致谢!

Use std::set_union and std::set_intersection , eg 使用std :: set_unionstd :: set_intersection ,例如

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; 其中setC是足够大小的输出数组; c points to one past the last element of the constructed range. c指向构造范围的最后一个元素之后的一个。

If you want cardinalities, c - setC is your answer. 如果你想要基数, c - setC就是你的答案。

I would recommend using something like std::vector for representation, and iterators instead of arrays/pointers/lengths in algorithm calls. 我建议使用像std::vector的表示法,并在算法调用中使用迭代器而不是数组/指针/长度。

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. 如果你想自己做,你会在上面的链接中找到“可能的实现”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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