一.集合
它是一個有序的容器,裡面的元素都是排序好的,支持插入,刪除,查找等操作
集合裡的所有元素都必須是唯一的值,不可重複
函式
範例
#include <iostream>
#include <set>
using namespace std;
int main(){
bool end=false;
set<int> de;
set<int>::iterator iter; //集合不可用索引值來存取資料,因此必須使用疊代器來指向元素資料
while(!end){
int s,d;
cout<<"1.加入資料 2.移除資料 3.結束 \n";
cin>>s;
switch(s){
case 1:
cout<<"輸入欲加入的資料:";
cin>>d;
de.insert(d);
break;
case 2:
if(de.size()>0){
iter=de.begin(); //end()?
cout<<"刪除:"<<*iter<<endl;
de.erase(*iter);
}
else
cout<<"無資料可刪除";
break;
case 3:
end=true;
for(iter=de.begin();iter!=de.end();iter++)
cout<<*iter<<"\t";
break;
cout<<endl;
}
}
}
補充·:多個集合的寫法
set<int> S[5]; //宣告5個集合
或是
set<int> S;
S.insert(55);
S.insert(10);
vector<set<int> > vec; //把set放在vector內,可新增多個set到vector
vec.push_back(S);
二.多重集合
和set類似,但允許有重複的資料
函式
範例
#include <iostream>
#include <set>
using namespace std;
int main (){
multiset<int> mset;
multiset<int>::iterator iter;
for (int i=1; i<6; i++)
mset.insert(i);
for (iter=mset.begin(); iter!=mset.end();iter++){
cout << *iter << ' ';
}
cout << endl;
for (int i=1; i<6; i++)
mset.insert(i);
for (iter=mset.begin(); iter!=mset.end();iter++){
cout << *iter << ' ';
}
cout << endl;
mset.erase(4);
for (iter=mset.begin(); iter!=mset.end();iter++){
cout << *iter << ' ';
}
cout << endl;
}
作業:
輸入N群數字,每群有M個數字,分別找出每群中最大的數字,計算所有最大數的總和。
請交exe執行檔