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

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

  • 39
    点赞
  • 186
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wym_king

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值