核心: set 是一個數學含義上的集合-----保證了每一個數的肯定性, 互異性, 不只如此, set 中的元素仍是有序的.函數
頭文件: #include <set>spa
拓展:因爲 set 內的元素是惟一的, 即不會出現相同值的元素,因此沒法存儲重複值.若是要想存儲重複值那麼能夠用 multiset.code
構造方法:對象
set<int> s1; //定義一個 int 類型的set, 默認排序是從小到大的. set<int> s2(s1); //定義一個 int 類型的set, 其初始值從集合 s1 拷貝而來. int arv[] = {1, 2, 3, 4}; set<int> s3(arv, arv + 4); //利用迭代器 [ begin(), end() ) 裏面的元素構建一個集合
利用仿函數構造:blog
set< int, greater<int> > s1; //能夠改變默認排序規則,按照降序排序
自定義比較函數構造:排序
const char* s[] = {"1", "2", "123232", "234", "321"}; struct cmp{ bool operator () (const char* a, const char* b) const { return strcmp(a, b) > 0; //按照字典序降序排列 } }; set<const char*, cmp> s1(s, s + 5, cmp());
集合的遍歷:數學
set<const char*, cmp>::iterator it;//迭代器類型和集合類型一致 for(it = s1.begin(); it != s1.end(); it++) { cout << *it << endl; }
集合的插入:it
s1.insert(value);//插入value,返回pair配對對象,能夠根據.second判斷是否插入成功,有可能由於重複元素而插入失敗
集合的刪除:io
s1.erase(value) //移除 s1 內元素值爲value的全部元素,返回移除的元素個數 s1.erase(&pos) //移除pos位置上的元素,無返回值 s1.erase(&first, &last) //移除迭代器[&first, &last)區間內的元素,無返回值 s1.clear() //移除容器 s1 內全部元素
集合的查找:ast
s1.count(value); //返回 s1 內元素值爲value的元素個數, 爲 」1「 或者 」0「 s1.find(value); //返回 s1 內 value 所在位置,找不到 value 將返回end();
本身定義類型必須重載 」<「
struct NODE{ int x; int y; bool operator < (const NODE& b) const { if(x == b.x) return y > b.y; //二級排序爲 y 的降序 return x < b.x; //一級排序爲 x 的升序 } }; set<NODE> s1;
其餘關於集合的操做:
s1.swap(s2); //將集合 s1 和集合 s2 互換 //得到兩個集合的 並 set<int> s1, s2, s3; set_union( s1.begin(), s1.end(), s2.begin(), s2.end(), insert_iterator< set<int> >(s3, s3.begin()) ); //得到兩個集合的 交 set<int> s1, s2, s3; set_intersection( s1.begin(), s1.end(), s2.begin(), s2.end(), insert_iterator< set<int> >(s3, s3.begin()) ); //得到兩個集合的 差 set<int> s1, s2, s3; set_difference( s1.begin(), //set_symmetric_difference 爲對稱差 即 A 交 B - A 並 B s1.end(), s2.begin(), s2.end(), insert_iterator< set<int> >(s3, s3.begin()) );