头文件:
#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 ;
}
说明,要查找的有序序列必须是合法的,已经被排序的序列。