離散數學-集合的交併差集運算--STL-set類
阿新 • • 發佈:2018-12-04
程式碼其實很簡單,我們只需要知道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 */