简体   繁体   English

如何找到集合的交集

[英]How to find intersection of sets

I have N number of sets of let us say integers. 我有N套让我们说整数。 Now I want a function, which finds me the intersection of those sets. 现在我想要一个函数,它找到了这些集合的交集。 For example, for the following 例如,对于以下内容

Set1 = { A, D, E, F, G, L }
Set2 = { N, K, E, G, B, C }
Set3 = { K, P, Q, E, F, G }
Set4 = { Z, Y, C, G, F, E }

Since E and G is in every set, I should get { E, G } as output. 由于E和G在每一组中,我应该得到{ E, G }作为输出。 What is the easiest way to do this. 最简单的方法是什么? I know it is not very difficult to write your own code to do this, but perhaps there is already an STL or any other library function to this, in which I'm interested. 我知道编写自己的代码来做这件事并不是很困难,但也许已经有了STL或其他任何库函数,我对此很感兴趣。

Two possible solutions I can think of 我能想到的两种可能的解决方案

  1. Store your sets in vectors. 将您的集合存储在向量中。 Sort the vectors using std::sort , and compute set intersection using std::set_intersection 使用std::sort对向量进行std::sort ,并使用std::set_intersection计算集合交集
  2. Store your sets in std::set , which causes the elements to be sorted anyway, and use std::set_intersection 将您的集存储在std::set ,这会导致元素无论如何都被排序,并使用std::set_intersection

See std::set_intersection . 请参见std::set_intersection (As pointed out already in the comments, you probably want intersection, not union.) (正如评论中已经指出的那样,你可能想要交集,而不是联盟。)

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

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