求两个整数集合的交集

这里要用到C++-STL中的set容器,这个容器的特点就是去重!

设计测试:给定两个集合

a[] = {1,2,3,4,5,6};

b[] = {4,5,6,7,8,9};

则集合的交集为4,5,6

代码如下,仅供参考:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <set>
 5 #define M 6
 6 #define N 6
 7 using namespace std;
 8 int main()
 9 {
10     int a[] = {1,2,3,4,5,6};
11     int b[] = {4,5,6,7,8,9};
12     set<int> sbA;
13     set<int> sbB;
14     int i =0,j = 0;
15     for(i = 0;i < M;i++)
16     {
17         sbA.insert(a[i]);
18     }
19 
20     for(j = 0;j<N;j++)
21     {
22         if(sbA.find(b[j]) != sbA.end())
23         {
24             sbB.insert(b[j]);
25         }
26     }
27     for(set<int>::iterator it = sbB.begin();it != sbB.end();it++)
28     {
29         cout<<*it <<" ";
30     }
31     cout<<endl;
32 
33 }
View Code
原文地址:https://www.cnblogs.com/sxmcACM/p/4392143.html