一、题目
二、解决方案
- 步骤如下:
- 将A和B分别存入到set中,然后创建一个tempSet集合存放交集的元素
- 遍历A的元素,如果A的这个元素在B中也出现过,将这个元素插入到tempSet集合中
- 遍历完成之后,tempSet存储了这两个集合的交集
#include <iostream>
#include <set>
using namespace std;
int main()
{
std::set<int> A = {2, 1, 8, 74, 1, 6, 5};
std::set<int> B = {3, 1, 7, 6, 9, 15, 74};
std::set<int> tempSet;
// 遍历A中所有的元素
for(const auto& elem : A)
{
// 如果这个元素也在B中, 将这个元素插入到tempSet中
if(B.count(elem))
{
tempSet.insert(elem);
}
}
// 遍历tempSet集合, 打印交集元素
for(const auto& elem : tempSet)
{
std::cout << elem << " ";
}
std::cout << std::endl;
return 0;
}