有關lower_bound()函數的使用


lower_bound()函數需要加載頭文件#include<algorithm>,其基本用途是查找有序區間中第一個大於或等於某給定值的元素的位置,其中排序規則可以通過二元關系來表示。

 

函數原型:
template<class ForwardIterator, class Type> ForwardIterator lower_bound( ForwardIterator _First, ForwardIterator _Last, const Type& _Val ); template<class ForwardIterator, class Type, class BinaryPredicate> ForwardIterator lower_bound( ForwardIterator _First, ForwardIterator _Last, const Type& _Val, BinaryPredicate _Comp );

傳入參數說明:
_First 要查找區間的起始位置
_Last 要查找區間的結束位置
_Val 給定用來查找的值
_Comp 自定義的表示小於關系的函數對象,根據某個元素是否滿足小於關系而返回true或者false

舉例說明:

 

#include<iostream>  
#include<vector>  
#include<algorithm>  
using namespace std;  
vector<int> v;  
int main()  
{  
    for (int i = 1; i < 4; i++)  
        v.push_back(2 * i);//注意此時v中的元素本身就是有序的  
    vector<int>::iterator it = lower_bound(v.begin(), v.end(), 3);  
    cout << *it << endl;  
    return 0;  
}  

  

上面的例子是針對容器的,注意返回的是距離元素3最近的指針it,輸出的是*it結果為元素4,假如我想得到位置而非具體的元素應該怎么辦呢?這里有一個指針偏移的技巧,只需要減去起始位置的指針即可,代碼如下:

#include<iostream>  
#include<vector>  
#include<algorithm>  
using namespace std;  
vector<int> v;  
int main()  
{  
    for (int i = 1; i < 4; i++)  
        v.push_back(2 * i);//注意此時v中的元素本身就是有序的  
    //vector<int>::iterator it = lower_bound(v.begin(), v.end(), 3);  
    int pos = lower_bound(v.begin(), v.end(), 3)-v.begin();  
    cout << pos<< endl;  
    return 0;  
}
 這時候返回pos就是所查找元素的位置,下標,這里查找到的元素應該是4在容器中的下標是1,所以輸出pos的結果就是1.對容器適用,對數組同樣適用:
#include<iostream>  
#include<algorithm>  
using namespace std;  
int main()  
{  
    int a[4] = { 2, 4, 6, 8 }; //注意此時a中的元素本身就是有序的  
    int * it = lower_bound(a,a+4,3);  
    cout << *it<< endl;  
    return 0;  
}  

返回位置只需要減掉數組的起始位置即可:

#include<iostream>  
#include<algorithm>  
using namespace std;  
int main()  
{  
    int a[4] = { 2, 4, 6, 8 }; //注意此時a中的元素本身就是有序的  
    //int * it = lower_bound(a,a+4,3);  
    int pos = lower_bound(a, a + 4, 3) - a;//a表示數組的起始位置  
    cout <<pos<< endl;  
    return 0;  
}  


結果和容器的時候是一樣的。

對於4個參數的情形,最后一個參數的自己定義的表示大小關系函數的對象,常用的逆序可以加載頭文件#include<functional>,里邊有一個greater<int>()函數即可對逆序求最近位置。假如說像上邊一樣元素為2 4 6 8,逆序則是8 6 4 2,那么求距離3最近表示的是與3最近的小於等於3的元素,輸出結果則是元素2了,代碼如下:

 

#include<iostream>  
#include<vector>  
#include<algorithm>  
#include<functional>  
using namespace std;  
vector<int> v;  
int main()   
{  
    for (int i = 4; i >0; i--)  
    v.push_back(2 * i);//注意此時v中的元素本身就是有序的  
    vector<int>::iterator it = lower_bound(v.begin(), v.end(), 3,greater<int>());  
    cout << *it << endl;  
    return 0;  
}   
說明,要查找的有序序列必須是合法的,已經被排序的序列。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM