首先,提到这个函数,是需要他自己的头文件<algorithm>
举个例子:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
bool cmp(int a,int b)
{
return a<b;
}
int main()
{
int temp;
int p[10]={2,4,6,5,5,5,9,3,3,3};
sort(p,p+10,cmp);
temp=lower_bound(p, p+10, 3)-p;
printf("%d\n",temp); //输出一
temp=upper_bound(p, p+10, 3)-p;
printf("%d\n",temp); //输出二
temp=*lower_bound(p, p+10, 6);
printf("%d\n",temp); //输出三
temp=*upper_bound(p, p+10, 6);
printf("%d\n",temp); //输出四
return 0;
}
sort后的p[10]={2,3,3,3,4,5,5,5,6,9};
认识一下这四个输出有什么不同:
输出一:1
输出二:4
输出三:6
输出四:9
那么让我们来认识一下“lower_bound-p”,“upper_bound-p”,“*lower_bound”与“*upper_bound”之间的区别
“lower_bound(p, p+n, c)-p”:得到第一个">=c"的数的位置
“upper_bound(p, p+n, c)-p”:得到第一个">c"的数的位置
“*lower_bound(p, p+n, c)”:得到第一个">=c"的数的值
“*upper_bound(p, p+n, c)”:得到第一个">c"的数的值
让我们用上述的结论举几个例子来证明一下:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
bool cmp(int a,int b)
{
return a<b;
}
int main()
{
int temp;
int p[10]={2,4,6,5,5,5,9,3,3,3};
sort(p,p+10,cmp);
temp=lower_bound(p, p+10, 4)-p;
printf("%d\n",temp);
temp=upper_bound(p, p+10, 4)-p;
printf("%d\n",temp);
temp=*lower_bound(p, p+10, 6);
printf("%d\n",temp);
temp=*upper_bound(p, p+10, 6);
printf("%d\n",temp);
return 0;
}
输出结果:
4
5
6
9