兩個整數集合A和B,求其交集


 兩個整數集合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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章