lower_bound函數的用法(STL庫函數)

函數lower_bound()在first和last中的前閉後開區間進行二分查找,返回大於或等於val的第一個元素位置。如果所有元素都小於val,則返回last的位置
舉例如下:
一個數組number序列爲:4,25,11,48,69,72,96,100.設要插入數字3,9,111.pos爲要插入的位置的下標

pos = lower_bound( number, number + 8, 3) - number,pos = 0.即number數組的下標爲0的位置。
pos = lower_bound( number, number + 8, 9) - number, pos = 1,即number數組的下標爲1的位置(即10所在的位置)。
pos = lower_bound( number, number + 8, 111) - number, pos = 8,即number數組的下標爲8的位置(但下標上限爲7,所以返回最後一個元素的下一個元素)。
所以,要記住:函數lower_bound()在first和last中的前閉後開區間進行二分查找,返回大於或等於val的第一個元素位置。如果所有元素都小於val,則返回last的位置,且last的位置是越界的!!~
返回查找元素的第一個可安插位置,也就是“元素值>=查找值”的第一個元素的位置

下面是示例程序,相信你可以看明白的。

#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>

using namespace std;
int main()
{
    int num[8]={4,25,11,48,69,72,96,100};
    int pos=lower_bound(num,num+8,3)-num;
    printf("符合條件的位置爲%d\n",pos);
    pos=lower_bound(num,num+8,9)-num;
    printf("符合條件的位置爲%d\n",pos);
    pos=lower_bound(num,num+8,111)-num;
    printf("符合條件的位置爲%d\n",pos);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章