1.關於set的概念
set 是STL中的集合。
集合我們都很熟悉,具有排異性,在這里set中也遵循這條規矩。 而且在set中,存在系統自動排序的操作。
2.set的常用函數
set 與 vector具有類似的用法
#include<set> //set 的頭文件
set<int> s; //聲明一個int型set變量,名為s
s.empty() //判定 s 是否為空
s.insert(1); //把數字1插入到s中 s.clear(); //清空s s.erase(1); //假若s存在1,則刪除1 s.begin(); //返回s中第一個元素地址 所以 *s.begin() s.end(); //返回s中最后一個元素地址 //這個特殊一點,返回的是s中最后一個元素的下一個元素 //所以 *(--s.end())是s最后一個元素 s.rbegin(); //rbegin可以看做逆向的第一個地址 相當於(--s.end()) 此處取的已經是s最后一個元素 s.rend(); //rend可以看做逆向的最后一個地址 相當於 s.begin() s.count(1); //計算s中1出現的次數,而次數只存在0與1,所以可以借來查找是否存在1 s.size(); //返回s中元素的個數 s.max_size(); //s最大能存元素的數目 s.find(2); //查找2 set<int>::iterator iter; //迭代器
erase(iterator) ,刪除定位器iterator指向的值
erase(first,second),刪除定位器first和second之間的值
erase(key_value),刪除鍵值key_value的值
//lower_bound(key_value) ,返回第一個大於等於key_value的定位器
//upper_bound(key_value), 返回最后一個大於等於key_value的定位器
#include <iostream> #include <set> using namespace std; int main() { set<int> s; s.insert(1); s.insert(3); s.insert(4); cout<<*s.lower_bound(2)<<endl; cout<<*s.lower_bound(3)<<endl; cout<<*s.upper_bound(3)<<endl; return 0; }
運行結果:
小結:set中的操作是不進行任何的錯誤檢查的,比如定位器的是否合法等等,所以用的時候自己一定要注意。
附上一道set的入門題:
hdu 1412 {A} + {B} http://acm.hdu.edu.cn/showproblem.php?pid=1412
Problem Description 給你兩個集合,要求{A} + {B}. 注:同一個集合中不會有兩個相同的元素. Input 每組輸入數據分為三行,第一行有兩個數字n,m(0<n,m<=10000),分別表示集合A和集合B的元素個數.后兩行分別表示集合A和集合B.每個元素為不超出int范圍的整數,每個元素之間有一個空格隔開. Output 針對每組數據輸出一行數據,表示合並后的集合,要求從小到大輸出,每個元素之間有一個空格隔開. Sample Input 1 2 1 2 3 1 2 1 1 2 Sample Output 1 2 3 1 2
AC代碼:
#include<iostream> #include<set> using namespace std; int main() { int n,m,x; set<int>s; set<int>::iterator it; while (cin>>n>>m){ s.clear(); for (int i=0;i<n+m;i++){ cin>>x; s.insert(x); } it=s.begin(); int cnt=s.size(); for (int i=1;i<=cnt;i++){ if (i==1) cout<<*it; else cout<<" "<<*it; it++; } cout<<endl; } return 0; }