抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

数组是升序的情况

例:1 3 5 7 7 10 11

lower_bound(begin, ned, key) — 得到第一个 >= key 的下标

upper_bound(begin, ned, key) — 得到第一个 > key 的下标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*************************************************************************
> File Name: 二分.cpp
> Author: 秃头王
> Mail: 1658339000@qq.com
> Created Time: 2022年05月06日 星期五 15时18分04秒
************************************************************************/

#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

int f[] = {1, 3, 5, 7, 7, 10, 11};

void printNumber(int *f, int n) {
for(int i = 0; i < n; i++) cout << f[i] << " ";
cout << endl;
return ;
}

int main() {
int n = sizeof(f) / sizeof(int);
printNumber(f, n);
int idx = -1;
idx = lower_bound(f, f + sizeof(f) / sizeof(int), 7) - f;
cout << "升序数组 - lower_bound - key = 7, idx = " << idx << endl;
idx = upper_bound(f, f + sizeof(f) / sizeof(int), 7) - f;
cout << "升序数组 - upper_bound - key = 7, idx = " << idx << endl;
idx = upper_bound(f, f + sizeof(f) / sizeof(int), 12) - f;
cout << "不存在的情况 - 升序数组 - upper_bound - key = 100, idx = " << idx << endl;


/***********************************************************************************************/

sort(f, f + n, greater<int>());
printNumber(f, n);
idx = lower_bound(f, f + sizeof(f) / sizeof(int), 7) - f;
cout << "降序数组 - lower_bound - key = 7, idx = " << idx << endl;
idx = upper_bound(f, f + sizeof(f) / sizeof(int), 7) - f;
cout << "降序数组 - upper_bound - key = 7, idx = " << idx << endl;
idx = upper_bound(f, f + sizeof(f) / sizeof(int), 12) - f;
cout << "不存在的情况 - 升序数组 - upper_bound - key = 100, idx = " << idx << endl;


return 0;
}

评论