C++算法一些常用的stl函数
1.lower_bound( )和upper_bound( )
lower_bound( )和upper_bound( )都是利用二分查找的方法在一個排好序的數(shù)組中進(jìn)行查找的
在從小到大的排序數(shù)組中,
lower_bound( begin,end,num):從數(shù)組的begin位置到end-1位置二分查找第一個大于或等于num的數(shù)字,找到返回該數(shù)字的地址,不存在則返回end。通過返回的地址減去起始地址begin,得到找到數(shù)字在數(shù)組中的下標(biāo)。
upper_bound( begin,end,num):從數(shù)組的begin位置到end-1位置二分查找第一個大于num的數(shù)字,找到返回該數(shù)字的地址,不存在則返回end。通過返回的地址減去起始地址begin,得到找到數(shù)字在數(shù)組中的下標(biāo)。
在從大到小的排序數(shù)組中,重載lower_bound()和upper_bound()
lower_bound( begin,end,num,greater<type>() ):從數(shù)組的begin位置到end-1位置二分查找第一個小于或等于num的數(shù)字,找到返回該數(shù)字的地址,不存在則返回end。通過返回的地址減去起始地址begin,得到找到數(shù)字在數(shù)組中的下標(biāo)。
upper_bound( begin,end,num,greater<type>() ):從數(shù)組的begin位置到end-1位置二分查找第一個小于num的數(shù)字,找到返回該數(shù)字的地址,不存在則返回end。通過返回的地址減去起始地址begin,得到找到數(shù)字在數(shù)組中的下標(biāo)。
greater<int>()表示內(nèi)置類型從大到小排序,less<int>()則是從小到大。
2.優(yōu)先隊列(priority_queue)
- top 訪問隊頭元素
- empty 隊列是否為空
- size 返回隊列內(nèi)元素個數(shù)
- push 插入元素到隊尾 (并排序)
- emplace 原地構(gòu)造一個元素并插入隊列
- pop 彈出隊頭元素
- swap 交換內(nèi)容
1)定義:priority_queue<Type, Container, Functional>
Type 就是數(shù)據(jù)類型,Container 就是容器類型(Container必須是用數(shù)組實現(xiàn)的容器,比如vector,deque等等,但不能用 list。STL里面默認(rèn)用的是vector),Functional 就是比較的方式,當(dāng)需要用自定義的數(shù)據(jù)類型時才需要傳入這三個參數(shù),使用基本數(shù)據(jù)類型時,只需要傳入數(shù)據(jù)類型,默認(rèn)是大頂堆
一般是:
?
注:從小到大排序是大頂堆,從大到小排序是小頂堆,而.top()取的是堆頂。
2)對于自定義類型:
#include <iostream> #include <queue> using namespace std;//方法1 struct tmp1 //運算符重載< {int x;tmp1(int a) {x = a;}bool operator<(const tmp1& a) const{return x < a.x; //大頂堆} };//方法2 struct tmp2 //重寫仿函數(shù) {bool operator() (tmp1 a, tmp1 b) {return a.x < b.x; //大頂堆} };int main() {tmp1 a(1);tmp1 b(2);tmp1 c(3);priority_queue<tmp1> d;d.push(b);d.push(c);d.push(a);while (!d.empty()) {cout << d.top().x << '\n';d.pop();}cout << endl;priority_queue<tmp1, vector<tmp1>, tmp2> f;f.push(c);f.push(b);f.push(a);while (!f.empty()) {cout << f.top().x << '\n';f.pop();} }轉(zhuǎn)自:https://blog.csdn.net/weixin_36888577/article/details/79937886
總結(jié)
以上是生活随笔為你收集整理的C++算法一些常用的stl函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SWAT模型高阶应用暨无资料地区建模、不
- 下一篇: R8500 MPv2 版本 刷梅林改版固