Files
python/TangDou/CSP-J/AcWingTraining/T1/LowerBoundUpperBound_Vector.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

41 lines
1.6 KiB
C++

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