C + + STL boundary function

Source: Internet
Author: User

C + + provides a class of STL functions to retrieve elements in an array, which is simpler and more widely used are binary_search,upper_bound and Lower_bound, which are included in the header file #include<algorithm >, use the following:

Stl
Lower_bound and Upper_bound
#include <iostream>
#include <algorithm>//the header file containing the two bounds functions
#include <cstdio>
using namespace Std;
int a[]={0,4,4,11,30,69,70,96,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);//Because the last x=y, so the output x and output y are the same
}
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);//Ibid.
}
int main ()
{
Std::ios::sync_with_stdio (false);//This sentence is used to speed up CIN and cout, but after use cin,cout can not be mixed with scanf,printf, so use 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;//to pay attention to the wording
Y=upper_bound (a,a+n,4)-A;
Z=binary_search (a,a+n,11);//Determine whether there is a return truth
W=binary_search (a,a+n,3);//return False value if not present
printf ("%d%d%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, note that the difference between the two functions is when the a[m]=aim is to shorten the interval forward or backward, which is related to the last X value.

C + + STL boundary function

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.