头文件:algorithm
int pos1=lower_bounda,a+n,k)-a;返回数组中第一个大于或等于k的值的下标
int pos2=upper_bound(a,a+n,k)-a;返回数组中第一个大于k的值的下标
注意作用对象是有序数组
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int a[10]={1,3,4,5,7,9,10,26,29,40};//有序数组
int pos1=lower_bound(a,a+10,5)-a;//返回数组中第一个大于或等于k的值的下标
int pos2=upper_bound(a,a+10,5)-a;//返回数组中第一个大于k的值的下标
cout<<"pos1"<<"="<<pos1<<endl;
cout<<"pos2"<<"="<<pos2<<endl;
return 0;
}
运行结果:
pos1=3
pos2=4
如果把要查找的数字K换成45,则会返回数组最后的下标位置
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int a[10]={1,3,4,5,7,9,10,26,29,40};//有序数组
int pos1=lower_bound(a,a+10,45)-a;//返回数组中第一个大于或等于k的值的下标
int pos2=upper_bound(a,a+10,45)-a;//返回数组中第一个大于k的值的下标
cout<<"pos1"<<"="<<pos1<<endl;
cout<<"pos2"<<"="<<pos2<<endl;
return 0;
}
运行结果:
pos1=10
pos2=10
vector容器
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
vector<int> a;
a.push_back(1);
a.push_back(3);
a.push_back(4);
a.push_back(5);
a.push_back(7);
a.push_back(9);
a.push_back(10);
a.push_back(26);
a.push_back(29);
a.push_back(40);
int pos1 = lower_bound(a.begin(),a.end(),5)-a.begin();
int pos2 = upper_bound(a.begin(),a.end(),5)-a.begin();
cout << "pos1"<<"="<<pos1<<endl;
cout << "pos2"<<"="<<pos2<<endl;
return 0;
}
运行结果:
pos1=3
pos2=4
同样如果把要查找的数字K换成45,则会返回数组最后的下标位置(我就不写了,和前面都一样)
set容器
set<int>a;
a.lower_bound(x); //查找大于等于 x 的元素中最小的一个,并返回指向该元素的迭代器。
a.upper_bound(x); //查找大于 x 的元素中最小的一个,并返回指向该元素的迭代器。
#include<iostream>
#include<algorithm>
#include<set>
using namespace std;
int main()
{
set<int> a;
a.insert(1);
a.insert(3);
a.insert(4);
a.insert(5);
a.insert(7);
a.insert(9);
a.insert(10);
a.insert(26);
a.insert(29);
a.insert(40);
set<int>::iterator it;
it = a.lower_bound(5);
cout<<"大于等于5的第一个值"<<"="<<*it<<endl;
it = a.upper_bound(5);
cout<<"大于5的第一个值"<<"="<<*it<<endl;
return 0;
}
运行结果:
大于等于5的第一个值=5
大于5的第一个值=7