C ++ STL boundary function, stl boundary Function
C ++ provides a class of STL functions to retrieve elements in an array. The simple and widely used functions include binary_search, upper_bound, and lower_bound, they are all included in the header file # include <algorithm>. The usage is as follows:
// STL
// Lower_bound and upper_bound
# Include <iostream>
# Include <algorithm> // header file containing the two Boundary Functions
# Include <cstdio>
Using namespace std;
Int a [] = {100,}, n = 8, m, x, y, z, w;
Void find_lower_bound (int aim)
{
Int x = 1, y = n, m;
While (x <y)
{
Int m = x + (y-x)/2;
If (a [m]> = aim) y = m;
Else x = m + 1;
}
Printf ("\ nlower_bound: % d", x); // The output x is the same as the output y because x is y.
}
Void find_upper_bound (int aim)
{
Int x = 1, y = n, m;
While (x <y)
{
Int m = x + (y-x)/2;
If (a [m] <= aim) x = m + 1;
Else y = m;
}
Printf ("\ nupper_bound: % d", x); // same as above
}
Int main ()
{
// Std: ios: sync_with_stdio (false); // This statement is used to speed up cin and cout. However, cout cannot be mixed with scanf and printf after cin is used, therefore, use it with caution.
// Cin> n;
// For (int I = 1; I <= n; I ++) scanf ("% d", & a [I]);
// Sort (a + 1, a + n + 1 );
// Cin> m;
X = lower_bound (a, a + n, 3)-a; // note the Writing Method
Y = upper_bound (a, a + n, 4)-;
Z = binary_search (a, a + n, 11); // determines whether the search exists and returns the true value.
W = binary_search (a, a + n, 3); // returns a false value if it does not exist.
Printf ("% d", x, y, z, w );
Find_lower_bound (3); // function prototype
Find_upper_bound (4); // function prototype
Return 0;
}
The function prototype here is actually a binary algorithm. The difference between the two functions is whether to shorten the range forward or backward when a [m] = aim, which is related to the final value of x.