C ++ STL boundary function, stl boundary Function

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.