Cho mảng đã sắp xếp và số x, đếm số phần tử x sử dụng upper_bound.
Ví dụ
#include <bits/stdc++.h>
using namespace std;
int countSmaller(int arr[], int n, int x) {
return upper_bound(arr, arr + n, x) - arr;
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr)/sizeof(arr[0]);
cout << countSmaller(arr, n, 45) << endl; // 4
cout << countSmaller(arr, n, 55) << endl; // 5
cout << countSmaller(arr, n, 4) << endl; // 0
return 0;
}
Đầu ra
4 5 0