lower_bound()的使用

头文件:algorithm

lower_bound()返回值是一个迭代器,返回指向大于等于key的第一个值的位置

对象:有序数组或容器

数组中使用

#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
	int a[]={1,2,3,4,5,7,8,9};
	printf("%d",lower_bound(a,a+8,6)-a); 
	
 return 0;	
} 
输出5
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
	int a[]={1,2,3,4,5,7,8,9};
	printf("%d",lower_bound(a,a+8,0)-a); 
	
 return 0;	
} 
输出0

将key换成10,所有val都小于key,返回last的位置

#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
	int a[]={1,2,3,4,5,7,8,9};
	printf("%d",lower_bound(a,a+8,10)-a); 
	
 return 0;	
} 
输出8

容器中使用:

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
 
int main()
{
    vector<int> A;
    A.push_back(1); 
    A.push_back(2); 
    A.push_back(3); 
    A.push_back(4); 
    A.push_back(5); 
    A.push_back(7); 
	A.push_back(8); 
	A.push_back(9); 
    
    int pos = lower_bound(A.begin() , A.end() , 6)-A.begin();
    cout << pos << endl;
    
    
    
    return 0;  
 }
输出5

注意:
lower_bound()函数是upper_bound()函数,它返回大于等于key的最后一个元素

也同样是要求有序数组,若数组中无重复元素,则两者返回值相同

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章