zoukankan      html  css  js  c++  java
  • 离散数学-集合的交并差集运算--STL-set类

    代码其实很简单,我们只需要知道set类的使用方法就可以了,比如迭代器的定义( set<T>::iterator it=a.begin() ),和简单的insert函数插入,以及find函数找到时返回对应的迭代器,找不到时返回该set的end。

    #include <iostream>
    #include <set>
    #define T int
    using namespace std;
    
    void ShowSet(set<T> V)
    {
    	set<T>::iterator it=V.begin();
    	for (;it!=V.end();it++) {
    		cout<<*it<<" ";
    	}
    	cout<<endl;
    }
    
    void inte(set<T>a,set<T>b)
    {
    	set<T>::iterator it=a.begin();
    	for (;it!=a.end();it++) {
    		if (b.find(*it)!=b.end()) {
    			cout<<*it<<" ";
    		}
    	}
    	cout<<endl;
    }
    
    void Sub(set<T>a,set<T>b)
    {
    	set<T>::iterator it=a.begin();
    	for (;it!=a.end();it++) {
    		if (b.find(*it)!=b.end())
    			continue;
    		cout<<*it<<" ";
    	}
    	cout<<endl;
    }
    
    void unio(set<T>a,set<T>b,set<T>c) 
    {
    	set<T>::iterator it=a.begin();
    	for (;it!=a.end();it++) {
    		c.insert(*it);
    	}
    	it=b.begin();
    	for (;it!=b.end();it++) {
    		c.insert(*it);
    	}
    	ShowSet(c);
    }
    
    int main()
    {
    	set<T> a,b,c;
    	T em;
    //	while (cin>>ch&&ch!='0')
    //	{
    //		a.insert(ch-'0');
    //	}
    //	ShowSet(a); 
    	int num1,num2;
    	cout<<"Please enter the number of the sets A and B."<<endl;
    	cin>>num1>>num2;
    	while (num1--) {
    		cin>>em;
    		a.insert(em);
    	}
    	while (num2--) {
    		cin>>em;
    		b.insert(em);
    	}
    	cout<<"Please enter the operation to be performed.I stands for intersection."<<endl
    	<<"U stands for union.S is the different set."<<endl;
    	char ch;
    	while (cin>>ch) {
    		if (ch=='I') {
    			inte(a,b);
    		}
    		else if (ch=='U') {
    			unio(a,b,c);
    		}
    		else if (ch=='S') {
    			bool is;
    			cout<<"Which one do you want to execute? A - B is true , B - A is false."<<endl;
    			cin>>is;
    			if (is==1)
    				Sub(a,b);
    			else 
    				Sub(b,a);
    		}
    		else 
    			cout<<"Input error!"<<endl;
    	}
    	return 0;
    }
    /*测试数据:
    5 5
    1 2 3 4 5
    1 2 7 8 9
    I
    U
    S
    1
    S
    0
    */ 
  • 相关阅读:
    打印水仙花数
    打印从1到k之间的所有素数
    Fibonacci数列小程序
    Fibonacci数
    水仙花数
    猴子吃桃问题
    5个数求最值—南阳acm
    三个数从小到大排序—南阳acm
    南阳acm奇偶数分离
    find the safest road--hdu1596
  • 原文地址:https://www.cnblogs.com/xyqxyq/p/10211355.html
Copyright © 2011-2022 走看看