STL SET 重载

函数test主要是是一般的set的输入输出

函数test_2_array主要是在set中的set也是可以去重复的

函数test3主要是对set中自定义对象如何重载

set的集合并

#include <set>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
struct node{ //自定义一个结构体node
set<int> myset;//一个成员set
int id;
node() 
{}
node(set<int> s,int i)//构造函数
{
	myset = s;
	id = i;
}
};
 bool operator < (const node & p1 ,const node & p2) //重载比较函数 重要  用来set有序时候的比较规则
    {  
		return p1.myset < p2.myset;
    } 
set<int> array_set;

int test()
{/*set 插入整形,自动进行排序,然后输出*/
	int n, i , j,p; 
	cin >>n;
	for(i = 0 ; i < n ; i++ )
	{
		cin>>p;
		array_set.insert(p);
	}
	
	for(set<int>::iterator it = array_set.begin(); it != array_set.end(); it ++)//利用迭代器进行迭代
	{
		cout<<*it<<" "<<endl;
	}
	return 0;
}
int test_2_array()
{
	set<set<int>> array_2; //二维的set,第一维set有int的自动比较,另外c++也重载了set类型的比较
	freopen("in.txt","r",stdin);//利用文件进行打开 打开in.txt 进行标准读,
	int n,m;
	int p;
	int i,j;
	cin>>n;
	for(i = 0 ; i < n ; i++)
	{
		cin>>m;
		set<int> temp;//定义一个set
		for(j = 0 ; j < m ; j ++)
		{
			cin>>p;
			temp.insert(p);
		}
		int size1 = array_2.size();
		 array_2.insert(temp); //插入set元素并自动进行排序
		int size2 = array_2.size();
		cout<< " " << size1 << " " <<size2 <<endl; 
	}
	set<int> ans ;
	set<int>::iterator ansit;
	for(set<set<int>>::iterator it1= array_2.begin(); it1 != array_2.end(); it1++)
	{
		
		ans.insert(it1->begin(),it1->end()); //用insert来实现集合的并操作
		for(set<int>::iterator it2 = (it1->begin()); it2  != it1->end(); it2 ++)
		{
			cout<< *it2 << " "; 
		}
		cout<<endl;
	}
	
	 std::cout << "The union has " << (ans.size()) << " elements:\n";
	for (ansit=ans.begin(); ansit!=ans.end(); ++ansit)
        std::cout << ' ' << *ansit;
	std::cout << '\n';
	fclose(stdin);
	return 1;
}
int test_3()
{//在set中插入自定义的元素 重载比较函数
	set<node> array_test;
	int i,j;
	freopen("in.txt","r",stdin);
	int n,m;
	int p;
	cin>>n;
	for(i = 0 ; i < n ; i++)
	{
		cin>>m;
		set<int> temp;
		for(j = 0 ; j < m ; j ++)
		{
			cin>>p;
			temp.insert(p);
		}
		int size1 = array_test.size();
		array_test.insert(node(temp,i));//利用构造函数进行元素的生命,然后插入
		int size2 = array_test.size();
		cout<< " " << size1 << " " <<size2 <<endl; 
	}
	return 1;
}
int main()
{
	test_3();
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值