Skip to content

Instantly share code, notes, and snippets.

@imoasislee
Created February 24, 2022 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imoasislee/fecc4b342c4c1e3ccb1baac37f7cb75b to your computer and use it in GitHub Desktop.
Save imoasislee/fecc4b342c4c1e3ccb1baac37f7cb75b to your computer and use it in GitHub Desktop.
//lower_bound upper_bound
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
struct Rule
{
bool operator() (const int & a1, const int & a2) const {
return a1%10 < a2%10;
}
};
void Print(int a[], int size)
{
for (int i=0; i<size; ++i)
{
cout << a[i] << ",";
}
cout << endl;
}
#define NUM 7
int main()
{
int a[NUM] = {12,5,3,5,98,21,7};
sort(a,a+NUM);
Print(a,NUM);
int * p = lower_bound(a,a+NUM,5);
cout<<*p<<","<<p-a<<endl; // 索引值=p-a 指针a是数组a[]的起始地址
p = upper_bound(a,a+NUM,5);
cout<<*p<<endl;
cout<<* upper_bound(a,a+NUM,13)<<endl;
sort(a,a+NUM,Rule());
Print(a,NUM);
cout<<* lower_bound(a,a+NUM,16,Rule())<<endl;
// ...
if(upper_bound(a,a+NUM,18,Rule())==a+NUM) // 没有找到
cout<<"not found"<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment