C++算法一些常用的stl函数
1.lower_bound( )和upper_bound( )
lower_bound( )和upper_bound( )都是利用二分查找的方法在一個排好序的數組中進行查找的
在從小到大的排序數組中,
lower_bound( begin,end,num):從數組的begin位置到end-1位置二分查找第一個大于或等于num的數字,找到返回該數字的地址,不存在則返回end。通過返回的地址減去起始地址begin,得到找到數字在數組中的下標。
upper_bound( begin,end,num):從數組的begin位置到end-1位置二分查找第一個大于num的數字,找到返回該數字的地址,不存在則返回end。通過返回的地址減去起始地址begin,得到找到數字在數組中的下標。
在從大到小的排序數組中,重載lower_bound()和upper_bound()
lower_bound( begin,end,num,greater<type>() ):從數組的begin位置到end-1位置二分查找第一個小于或等于num的數字,找到返回該數字的地址,不存在則返回end。通過返回的地址減去起始地址begin,得到找到數字在數組中的下標。
upper_bound( begin,end,num,greater<type>() ):從數組的begin位置到end-1位置二分查找第一個小于num的數字,找到返回該數字的地址,不存在則返回end。通過返回的地址減去起始地址begin,得到找到數字在數組中的下標。
greater<int>()表示內置類型從大到小排序,less<int>()則是從小到大。
2.優先隊列(priority_queue)
- top 訪問隊頭元素
- empty 隊列是否為空
- size 返回隊列內元素個數
- push 插入元素到隊尾 (并排序)
- emplace 原地構造一個元素并插入隊列
- pop 彈出隊頭元素
- swap 交換內容
1)定義:priority_queue<Type, Container, Functional>
Type 就是數據類型,Container 就是容器類型(Container必須是用數組實現的容器,比如vector,deque等等,但不能用 list。STL里面默認用的是vector),Functional 就是比較的方式,當需要用自定義的數據類型時才需要傳入這三個參數,使用基本數據類型時,只需要傳入數據類型,默認是大頂堆
一般是:
?
注:從小到大排序是大頂堆,從大到小排序是小頂堆,而.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 //重寫仿函數 {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();} }轉自:https://blog.csdn.net/weixin_36888577/article/details/79937886
總結
以上是生活随笔為你收集整理的C++算法一些常用的stl函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SWAT模型高阶应用暨无资料地区建模、不
- 下一篇: VC和TC的区别