已知集合A和集合B中的元素,设计三个算法,求A交B的结果,A并B的结果,A-B的结果。
在文件a.txt中第一行为A集合中的元素个数,第二行为A集合中的元素。
在文件b.txt中第一行为B集合中的元素个数,第二行为B集合中的元素。
代码:
#include<iostream>
#include<cstdio>
#include<set>
#include<fstream>
#include<algorithm>
#include<iterator>
using namespace std;
int main()
{
//fstream filea("A:\\a.txt");
//fstream fileb("A:\\b.txt");
FILE *fp1;
fp1=fopen("A:\\a.txt","rw+");
FILE *fp2;
fp2=fopen("A:\\b.txt","rw+");
set<int> A;
set<int> B;
set<int> C,D,E;
set<int>::iterator op;
int na, nb;
/*
filea>> na;
for (int i = 0; i < na; i++) {
int temp;
filea >> temp;
A.insert(temp);
}
fileb>> nb;
for (int i = 0; i < nb; i++) {
int temp;
fileb >> temp;
B.insert(temp);
}
*/
while(!feof(fp1)){
int num1;
fscanf(fp1,"%d",&num1);
for(int i=0;i<num1;i++){
int number;
fscanf(fp1,"%d",&number);
A.insert(number);
}
}
while(!feof(fp2)){
int num2;
fscanf(fp2,"%d",&num2);
for(int i=0;i<num2;i++){
int number;
fscanf(fp2,"%d",&number);
B.insert(number);
}
}
set_intersection(A.begin(), A.end(), B.begin(), B.end(), inserter(C, C.begin()));
for (op = C.begin(); op!= C.end(); op++)
{
//if ( != C2.begin())cout << ", ";
cout << *op<<' ';
}
cout<< endl;
set_union(A.begin(), A.end(), B.begin(), B.end(), inserter(D, D.begin()));
for (op = D.begin(); op != D.end(); op++)
{
//if ( != C2.begin())cout << ", ";
cout << *op << ' ';
}
cout << endl;
set_difference(A.begin(), A.end(), B.begin(), B.end(), inserter(E, E.begin()));
for (op = E.begin(); op != E.end(); op++)
{
//if ( != C2.begin())cout << ", ";
cout << *op << ' ';
}
cout<<endl;
fclose(fp1);
fclose(fp2);
system("pause");
return 0;
}