c++中的upper_bound()和lower_bound()的使用
c++中通过upper_bound()和lower_bound()寻找数组中某一个数值的位置,主要包含三个参数:
1.一个数组元素的地址(或者数组名来表示这个数组的首地址,用来表示这个数组的开头比较的元素的地址,不一定要是首地址,只是用于比较的“首”地址),
2.一个数组元素的地址(对应的这个数组里边任意一个元素的地址,表示这个二分里边的比较的"结尾’地址),
3.就是一个你要查找的那个数。
上代码:
#include
#include<stdio.h>
#include
#include
#include
#pragma warning(disable:4996)
using namespace std;
int k, n = 10;
int a[10] = { 1,1,1,3,3,5,5,5,5,6 };
//lower_bound()
//int main()
//{
// for (int i = 0; i < n; i++)cout << a[i] << " “;
// cout << endl;
// while (scanf(”%d", &k))
// {
// cout << k << “的第一个大于等于它的位置在” << ((lower_bound(a, a + n, k)) - a) + 1 << endl;
// }
//}
//upper_bound()
int main()
{
for (int i = 0; i < n; i++)cout << a[i] << " “;
cout << endl;
while (scanf(”%d", &k))
{
cout << k << “的第一个大于它的位置在” << ((upper_bound(a, a + n, k)) - a) + 1 << endl;
}
}
其中lower_bound()是要查找数大于等于的位置,upper_bound()是大于数组里面某个数的位置。具体代入上述代码自己验证,对于做查找很方便。