lower_bound()函数需要加载头文件#include<algorithm>,其基本用途是查找有序区间中第一个大于或等于某给定值的元素的位置,其中排序规则可以通过二元关系来表示。
函数原型:
template<class ForwardIterator, class Type> ForwardIterator lower_bound( ForwardIterator _First, ForwardIterator _Last, const Type& _Val ); template<class ForwardIterator, class Type, class BinaryPredicate> ForwardIterator lower_bound( ForwardIterator _First, ForwardIterator _Last, const Type& _Val, BinaryPredicate _Comp );
传入参数说明:
_First 要查找区间的起始位置
_Last 要查找区间的结束位置
_Val 给定用来查找的值
_Comp 自定义的表示小于关系的函数对象,根据某个元素是否满足小于关系而返回true或者false
举例说明:
- #include<iostream>
- #include<vector>
- #include<algorithm>
- using namespace std;
- vector<int> v;
- int main()
- {
- for (int i = 1; i < 4; i++)
- v.push_back(2 * i);//注意此时v中的元素本身就是有序的
- vector<int>::iterator it = lower_bound(v.begin(), v.end(), 3);
- cout << *it << endl;
- return 0;
- }
上面的例子是针对容器的,注意返回的是距离元素3最近的指针it,输出的是*it结果为元素4,假如我想得到位置而非具体的元素应该怎么办呢?这里有一个指针偏移的技巧,只需要减去起始位置的指针即可,代码如下:
- #include<iostream>
- #include<vector>
- #include<algorithm>
- using namespace std;
- vector<int> v;
- int main()
- {
- for (int i = 1; i < 4; i++)
- v.push_back(2 * i);//注意此时v中的元素本身就是有序的
- //vector<int>::iterator it = lower_bound(v.begin(), v.end(), 3);
- int pos = lower_bound(v.begin(), v.end(), 3)-v.begin();
- cout << pos<< endl;
- return 0;
- }
- #include<iostream>
- #include<algorithm>
- using namespace std;
- int main()
- {
- int a[4] = { 2, 4, 6, 8 }; //注意此时a中的元素本身就是有序的
- int * it = lower_bound(a,a+4,3);
- cout << *it<< endl;
- return 0;
- }
- #include<iostream>
- #include<algorithm>
- using namespace std;
- int main()
- {
- int a[4] = { 2, 4, 6, 8 }; //注意此时a中的元素本身就是有序的
- //int * it = lower_bound(a,a+4,3);
- int pos = lower_bound(a, a + 4, 3) - a;//a表示数组的起始位置
- cout <<pos<< endl;
- return 0;
- }
结果和容器的时候是一样的。
对于4个参数的情形,最后一个参数的自己定义的表示大小关系函数的对象,常用的逆序可以加载头文件#include<functional>,里边有一个greater<int>()函数即可对逆序求最近位置。假如说像上边一样元素为2 4 6 8,逆序则是8 6 4 2,那么求距离3最近表示的是与3最近的小于等于3的元素,输出结果则是元素2了。
// 对作者这里的表述不是很认同,emmm...测了很多,也一直查不到准确的说法,还是不用了。。
代码如下:
- #include<iostream>
- #include<vector>
- #include<algorithm>
- #include<functional>
- using namespace std;
- vector<int> v;
- int main()
- {
- for (int i = 4; i >0; i--)
- v.push_back(2 * i);//注意此时v中的元素本身就是有序的
- vector<int>::iterator it = lower_bound(v.begin(), v.end(), 3,greater<int>());
- cout << *it << endl;
- return 0;
- }