二分查找 查找是否存在某数
bool binary_search(开始位置,结束位置,查找元素,自定义函数);
前提:升序(验证如下)
寻找小于等于某数的第一个数:
(返回迭代器)lower_bound (开始位置,结束位置,查找元素);
找到返回元素位置,未找到返回最后一个元素后的位置
寻找小于等于某数的第最后一个数;
(返回迭代器)upper_bound(开始位置,结束位置,查找元素);
找到返回元素位置,未找到返回最后一个元素后的位置
#include <iostream>
using namespace std;
int main() {
//数组元素个数为8
int a[] = { 1,4,4,4,5,7,8,9 };
int b[] = { 3,3,4,5,7,7,7,9 };
int c[] = { 9,7,7,7,5,4,3,3 };
int aa = lower_bound(a, a + 8, 4) - a;
int bb = upper_bound(b, b + 8, 7) - b;
int cc = upper_bound(c, c + 8, 7) - c;
printf("%d %d %d\n", aa, a[aa - 1], a[aa]);
printf("%d %d %d\n",bb, a[bb], a[bb + 1]);
printf("%d %d %d", cc, a[cc], a[cc + 1]);
return 0;
}