ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมนับองค์ประกอบที่น้อยกว่าค่าที่กำหนดในอาร์เรย์ที่เรียงลำดับแล้วใน C++
ให้ตัวเลขหนึ่ง ต้องนับองค์ประกอบทั้งหมดในอาร์เรย์ที่เรียงแล้วซึ่งน้อยกว่าตัวเลขที่ให้มา
ตัวอย่างโค้ด
#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;
cout << countSmaller(arr, n, 55) << endl;
cout << countSmaller(arr, n, 4) << endl;
return 0;
}
เอาต์พุต
4 5 0