lower_bound的使用
lower_bound()返回一个 iterator 它指向在[first,last)标记的有序序列中可以插入value,
返回一个不小于value 的位置。该函数为C++ STL内的函数。但大前提是要查找的区间一定要是有序的!一定要是有序的! 一定要是有序的!
函数原型
第一个版本:
ForwardIterator lower_bound(ForwardIterator first,ForwardIterator last,const T &val);
第二个版本:(需加头文件#include<algoritm>)
ForwardIterator lower_bound(ForwardIterator first,ForwardIterator last,const T &val,Compare cmp);
第二个版本中,函数中第四的参数 是为了按照自己所规定的顺序查找(例如想要按降序查找),如果不加这个cmp,那么将默认为升序的顺序
实例一:
#include<iostream>
using namespace std;
int main()
{
int a[10];
a[0]=1;
a[1]=2;
a[2]=3;
a[3]=6;
a[4]=7;
int *p=lower_bound(a,a+4,4);
for(int i=0;i<5;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
cout<<*p<<endl;
//可见lower_bound函数并不能直接插入,但能够找到在一组有序序列中(或按一定规则排序的序列中),找到比目标数值刚好大一点的数的位置)
//如果是STL,可以无损插入,用insert函数
return 0;
}
实例二
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector <int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(6);
v.push_back(8);
vector<int>::iterator it;
it=lower_bound(v.begin(),v.end(),7);
cout<<"返回的位置为"<<*it<<endl;
int s=v.size();
for(int i=0;i<s;i++)
cout<<v[i]<<" ";
cout<<endl;
v.insert(it,7);
s=v.size();
for(int i=0;i<s;i++)
cout<<v[i]<<" ";
cout<<endl;
return 0;
}
实例三:加cmp的情况
用cmp的时候,一定要加头文件#include<algorithm>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
return a>b;
}
int main()
{
vector <int> v;
v.push_back(8);
v.push_back(7);
v.push_back(3);
v.push_back(2);
v.push_back(1);
vector<int>::iterator it;
it=lower_bound(v.begin(),v.end(),4,cmp);
cout<<"返回的位置为"<<*it<<endl;
int s=v.size();
for(int i=0;i<s;i++)
cout<<v[i]<<" ";
cout<<endl;
v.insert(it,4);
s=v.size();
for(int i=0;i<s;i++)
cout<<v[i]<<" ";
cout<<endl;
return 0;
}
如果有什么错误,欢迎指正,学习