现在的位置: 首页 > 综合 > 正文

两个整数集合A和B,求其交集

2017年12月15日 ⁄ 综合 ⁄ 共 453字 ⁄ 字号 评论关闭
 两个整数集合A和B,求其交集。
 
1. 读取整数集合A中的整数,将读到的整数插入到map中,并将对应的值设为1。
 
2. 读取整数集合B中的整数,如果该整数在map中并且值为1,则将此数加入到交集当中,并将在map中的对应值改为2
 
通过更改map中的值,避免了将同样的值输出两次。
下面为源码:
#include <iostream>
#include <map>
using namespace std;

int main(void)
{
	map<int, int> map;
	int unin[10], cnt=0;
	int a[] = {2, 3, 7, 8, 4, 10};
	int b[] = {1, 2, 3, 4, 10, 6};
	int i=0;
	for(i=0; i<6; i++)
		map[a[i]] = 1;
	for(i=0; i<6; i++)
	{
		if(map.find(b[i])->second==1)
		{
			unin[cnt++] = b[i];
			map[b[i]]++;
		}
	}
	for(i=0; i<cnt; i++)
		cout << unin[i] << " ";
	cout << endl;
	return 0;
}

抱歉!评论已关闭.