国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 股票| 萝北县| 安顺市| 景泰县| 景德镇市| 长春市| 娄烦县| 襄城县| 裕民县| 静海县| 伊宁市| 揭西县| 霞浦县| 日喀则市| 冕宁县| 两当县| 龙泉市| 灌南县| 上虞市| 浪卡子县| 巨鹿县| 温州市| 铁力市| 固阳县| 赤峰市| 个旧市| 滕州市| 梅河口市| 那坡县| 页游| 潢川县| 惠安县| 武川县| 池州市| 漳平市| 昔阳县| 镇安县| 海口市| 湖南省| 鄂托克旗| 垦利县|