Hzu挑战自我


私信TA

用户名:gxhzxyjsj

访问量:90939

签 名:

2023终究会过去,期待2024!

等  级
排  名 8
经  验 26257
参赛次数 58
文章发表 157
年  龄 0
在职情况 教师
学  校 贺州学院
专  业 软件工程

  自我简介:

弱鸡一个,继续努力!

解题思路:

    可以使用STL的set,set集合可以实现自动从小到大排序,而且集合set中有如下函数:

    set_intersection(取两集合交集)

    set_union(取两集合并集)

    set_difference(取两集合差集)。

注意事项:

    (1)这几个函数的参数一样。

    (2)例如:set_union(x1.begin(), x1.end(), x2.begin(), x2.end(), inserter(x, x.end())),前两个参数是集合x1的头尾,再依次是集合x2的头尾,最后一个参数就是将集合x1和集合x2取合集后存入集合x中。


参考代码:

#include <bits/stdc++.h>
using namespace std; 
void input(set<int> &X) //input函数把数据输入到集合X中 
{
	int n,number;
	cin>>n;
	while(n--)
	{
		cin>>number;
		X.insert(number);		
	} 
}
void output(set<int> X) //output函数把集合X中的数据输出 
{
	set<int>::iterator it;
	for(it=X.begin();it!=X.end();it++)
		cout<<*it<<" ";
	cout<<endl;
} 
int main()         
{ 
	int n,m; 
	set <int> A,B,AnB,AuB,A_B;
	input(A);
	input(B);
	set_intersection( A.begin(),A.end(),B.begin(),B.end(),inserter( AnB, AnB.end() ) );
	output(AnB);
	set_union( A.begin(),A.end(),B.begin(),B.end(),inserter( AuB, AuB.end() ) );
	output(AuB);
	set_difference( A.begin(),A.end(),B.begin(),B.end(),inserter( A_B, A_B.end() ) );
	output(A_B);	
	return 0;
}


 

0.0分

9 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区