国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

STL 二分法 upper_bound()與lower_bound()使用方法

2019-11-08 02:40:46
字體:
供稿:網(wǎng)友

   lower_bound( first, last,val)算法返回一個非遞減序列[first, last)中的第一個大于等于值val的位置

的迭代器

       upper_bound(first, last, val)算法返回一個非遞減序列[first, last)中第一個大于val的位置的迭代器。

    使用頭文件

     #include<iostream>

     using namespace std;

測試樣例

#include<iostream>#include<algorithm>using namespace std;int main(){    int a[]={0,1,2,4,5,6,7,8,9,10};    //返回對應元素    cout<<*upper_bound(a,a+10,3)<<endl;   //4 第一個大于    cout<<*lower_bound(a,a+10,3)<<endl;   //4 第一個大于等于    //返回對應下標    cout<<upper_bound(a,a+10,4)-a<<endl;   //4 第一個大于    cout<<lower_bound(a,a+10,4)-a<<endl;   //3 第一個大于等于    cout<<upper_bound(a,a+10,-1)-a<<endl;   //0 未找到將返回第一個    cout<<lower_bound(a,a+10,-1)-a<<endl;   //0 未找到將返回第一個    cout<<upper_bound(a,a+10,11)-a<<endl;   //10 未找到將返回最后    cout<<lower_bound(a,a+10,11)-a<<endl;   //10 未找到將返回最后    /*    注意:    兩個函數(shù)使用時,必須確定序列為非遞減序列,否則會發(fā)生錯誤    */    return 0;}

      這兩個函數(shù)還分別有一個重載函數(shù),可以接受第四個參數(shù)。如果第四個參數(shù)傳入greater<Type>(),其中Type改成對應類型,可以用于查找非遞增序列

測試樣例

#include<iostream>#include<algorithm>using namespace std;int main(){    int a[]={10,9,8,7,6,5,4,2,1,0};    cout<<upper_bound(a,a+10,4,greater<int>())-a<<endl;   //7 返回第一個小于    cout<<lower_bound(a,a+10,4,greater<int>())-a<<endl;   //6 返回第一個小于等于    cout<<upper_bound(a,a+10,-1,greater<int>())-a<<endl;   //10 未找到將返回最后    cout<<lower_bound(a,a+10,-1,greater<int>())-a<<endl;   //10 未找到將返回最后    cout<<upper_bound(a,a+10,11,greater<int>())-a<<endl;   //0 未找到將返回第一個位置    cout<<lower_bound(a,a+10,11,greater<int>())-a<<endl;   //0 未找到將返回第一個位置    return 0;}   兩個函數(shù)配合使用可以進行查找 有序序列中的元素個數(shù)

使用樣例

#include<iostream>#include<algorithm>using namespace std;int main(){    int a[]={0,1,2,3,5,5,5,6,7};   //查找元素 5 的個數(shù)    cout<<upper_bound(a,a+10,5)-lower_bound(a,a+10,5)<<endl;    return 0;}


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 白城市| 嘉定区| 泰宁县| 清原| 上高县| 新化县| 涪陵区| 东安县| 阿图什市| 武鸣县| 曲麻莱县| 漳州市| 灵璧县| 惠州市| 焦作市| 杭锦后旗| 家居| 怀远县| 义乌市| 大埔县| 明星| 洪江市| 玉田县| 寿光市| 德庆县| 来凤县| 鹤岗市| 手机| 铁岭市| 博爱县| 瑞金市| 灌南县| 扶风县| 朝阳县| 东乌| 昌黎县| 望奎县| 瑞丽市| 彩票| 江油市| 凤凰县|