简体   繁体   中英

How to find intersection of sets

I have N number of sets of let us say integers. 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. 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.

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
  2. Store your sets in std::set , which causes the elements to be sorted anyway, and use std::set_intersection

See std::set_intersection . (As pointed out already in the comments, you probably want intersection, not union.)

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