45 lines
1.6 KiB
C++
45 lines
1.6 KiB
C++
#include <bits/stdc++.h>
|
|
using namespace std;
|
|
const int N = 10;
|
|
int arr[N] = {1, 2, 4, 4, 4, 6, 8, 10};
|
|
const int n = 8;
|
|
const int target = 4;
|
|
|
|
int main() {
|
|
// lower_bound
|
|
int *lower = lower_bound(arr, arr + n, target);
|
|
cout << "lower_bound of " << target << " is at index: " << (lower - arr) << endl;
|
|
|
|
// upper_bound
|
|
int *upper = upper_bound(arr, arr + n, target);
|
|
cout << "upper_bound of " << target << " is at index: " << (upper - arr) << endl;
|
|
|
|
// 找到最后一个小于 target 的元素
|
|
if (lower != arr) {
|
|
int *last_less = lower - 1;
|
|
cout << "Last element less than " << target << " is " << *last_less << " at index " << (last_less - arr) << endl;
|
|
} else {
|
|
cout << "No element is less than " << target << endl;
|
|
}
|
|
|
|
// 找到最后一个小于等于 target 的元素
|
|
if (upper != arr) {
|
|
int *last_less_equal = upper - 1;
|
|
cout << "Last element less than or equal to " << target << " is " << *last_less_equal
|
|
<< " at index " << (last_less_equal - arr) << endl;
|
|
} else {
|
|
cout << "No element is less than or equal to " << target << endl;
|
|
}
|
|
|
|
// 查找元素是否存在
|
|
if (lower != arr + n && *lower == target)
|
|
cout << target << " exists in the array at index " << (lower - arr) << endl;
|
|
else
|
|
cout << target << " does not exist in the array." << endl;
|
|
|
|
// 统计目标值出现个数
|
|
int count = upper - lower;
|
|
cout << "Count of " << target << " is: " << count << endl;
|
|
|
|
return 0;
|
|
} |