首页 技术 正文
技术 2022年11月11日
0 收藏 498 点赞 2,310 浏览 1536 个字

头文件:

#include<algorithm>

作用:

查找第一个大于或等于给定数的元素或位置

在从小到大的排列数组中

注意注意:

  是排列好的,

  一般都是从小到大,

  但从大到小也可以,

  只不过做法与常规的从小到大的不太一样

查找有序区间中第一个大于或等于某给定值的元素的位置

其中排序规则可以通过二元关系来表示

代码举例:

1.针对容器

(1).得到具体的元素:

#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> v;
int main()
{
for(int i = ;i < ;i++)
v.push_back( * i);//注意:此时v中的元素本身就是有序的
vector<int>::iterator it = lower_bound(v.begin(),v.end(),);
printf("%d\n",*it);
return ;
}

(2).得到位置:

用到了指针偏移的技巧,只需要前去起始位置的指针即可

#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
vector<int> v;
int main()
{
for(int i = ;i < ;i++)
v.push_back(i * );//注意:此时v中的元素本身就是有序的
int pos = lower_bound(v.begin(),v.end(),) - v.begin();
printf("%d\n",pos);
return ;
}
这时候返回pos就是所查找元素的位置,下标,
这里查找到的元素应该是4在容器中的下标是1,
所以输出pos的结果就是12.针对数组

返回元素:

#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
int a[] = {,,,};
int *it = lower_bound(a,a+,);
printf("%d\n",*it);
return ;
}

返回位置:

#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
int a[] = {,,,};//注意:初始化中的元素本身就是有序的
int pos = lower_bound(a,a+,)-a;
printf("%d\n",pos);
return ;
}

以上都是针对从小到大排列好的

————————————————————————————————————————

下面是从大到小排列好的

函数:

  greater<int>()

头文件:
  #include<functional>

假如说像上边一样元素为2 4 6 8,

逆序则是8 6 4 2,

那么求距离3最近表示的是与3最近的小于等于3的元素,

输出结果则是元素2了,

代码如下:

#include<cstdio>
#include<algorithm>
#include<vector>
#include<functional>
using namespace std;
vector<int> v;
int main()
{
for(int i = ;i > ;i--)
v.push_back(i * );
vector<int>::iterator it = lower_bound(v.begin(),v.end(),,greater<int>());
printf("%d\n",*it);
return ;
}
说明,要查找的有序序列必须是合法的,已经被排序的序列。
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,145
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,617
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,461
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,236
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,871
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,952