STL upper_bound (), lower_bound () function learning + self-implementation
In STL, these two functions are used to find the position of an element in an ordered array. In simple usage, upper_bound (begin, end, key) and start is the start point of the search, end is the end point, key is the key value, and lower_bound () is used in the same way. The upper_bound () function returns the first value greater than the value to be searched (or the next position of this element ), lower_bound is a location smaller than or equal to the keyword (or the location where the keyword appears for the first time ),
# Include
Using namespace std; const int maxn = 2222; int a [maxn]; int n; int my_upper_bound (int num) {int l = 0; int h = n-1; while (l <= h) {int mid = (l + h)/2; if (numa [mid]) l = mid + 1; else h = mid-1 ;} return l;} int main () {cin> n; for (int I = 0; I
> A [I]; printf ("my_upper_bound (4) at % d \ n", my_upper_bound (4); printf ("my_lower_bound (4) location in % d \ n ", my_lower_bound (4); printf (" lower_bound (4) location in % d \ n ", lower_bound (a, a + n, 4) -a); printf ("upper_bound (4) at % d \ n", upper_bound (a, a + n, 4)-a); return 0 ;}