STL初步
頭文件
sort
sort(數組名+n,數組名+m)// 能,m爲整數 ,適用於基本類型 ,範圍爲下標n到m-1,下標m不參與排序
//自定義排序
struct rule{
bool operator(const T & a ,const T & b)(){
// 若a在b前,則返回true,否則false
}
};
sort(a,a+sizeof(a),rule());
二分查找
在排好序的數組上進行二分查找
等於的含義:a等於b 等價於a>b 和a<b都不成立。
binary_search(a,a+a.szie(),key,rule());
lower_bounder(a,a+a.szie(),key);// 查找下界,返回數組存儲元素類型的指針,是大於查找值下標最小的
lower_bounder(a,a+a.szie(),key,rule());//查找排在可key後面的元素,查不到,指向下標爲a+size()的元素
upper_bounder
平衡二叉樹
增,刪,查都能在複雜度完成
四種排序容器
- multiset
- set
- multimap
- map
multiset 上的迭代器:++,–,!=,==,不能比大小,不能加減整數,不能相加減
#include <set> // multiset ,set
multiset<T> st;
int a[];
for()
st.insert(a[i]);//插入的是複製品
multiset<int>::iterator i;
for(i= st.begin();i!=st.end();i++)
cout<<*i;
i = st.find(32)
if(i == st.end())
cout<<"not find";
else
st.eraser(i);
multiset<int rule> st2;
set和multiset的區別:set中不能有重複的元素。(重複元素:a和b重複 ,即a等於b,a>b和 a<b都不成立。
set可能插入失敗
pair<set<int>::iterator,bool> result = st.inset(2);
if(! result.second)
cout<<"exists";
pair<T1,T2>
struct{
T1 first;
T2 second;
};
multimap<T1,T2> mp;
struct{
T1 first;
T2 second;
};
multimap是按first排序,按first查找
默認是升序
map不能有關鍵字重複
可以使用[],下標爲關鍵字,返回second
reference
北大 程序設計與算法(一)C語言程序設計 mooc https://www.icourse163.org/course/PKU-1001553023