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

将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

vector:        

#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值大的最后一个元素

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

猜你喜欢

转载自blog.csdn.net/qq_41603898/article/details/81603327