C++STL中用到二分查找的函数

首先数组必须是有序的!

1.binary_search()(查找某个值在数组中是否存在)

使用方法:binary_search(list,list+n,a)

list为数组,a为要查询的值,n为数组大小

binary_search返回的是真假值,就是它只判断这个数组中是否存在这个数;

代码:


/*

*/
#include<map>
#include<set>
#include <vector>
#include<stack>
#include<queue>
#include<cmath>
#include<string>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll unsigned long long
#define inf 0x3f3f3f
#define esp 1e-8
#define bug {printf("mmp\n");}
#define mm(a,b) memset(a,b,sizeof(a))
#define T() int test,q=1;scanf("%d",&test); while(test--)
const int maxn=1e4+10;
const double pi=acos(-1.0);
const int N=201;
const int mod=1e9+7;
int b[]={1,2,3,4,5,6,7,8};
int main()
{
    int a;
    cin>>a;
    bool s=binary_search(b,b+8,a);
    cout<<s<<endl;
    return 0;
}

如果我们想要查找它的位置该怎么办??

使用 lower_bound和upper_bound,第一个是找到第一个大于等于要查找的数的位置,第二个是找到大于要查找的数的位置

两者结合使用便可以得到想要的结果了

2. lower_bound查找第一个大于或等于某个元素的位置

使用方法:lower_bound(list,list+n,a)

list为数组,n为数组大小,a为要查询的值

注意事项:lower_bound()返回的是指针,所以所以减去数组的指针就是int变量了

当查询到值存在时,返回的是第一个大于等于查询值的下标,注意是下标(0-n)

当查询值不存在且所有的值均大于要查询的值,返回0,

当查询的值不存在且所有值均小于要查询的值时,返回最后一个元素的下一个元素下标

代码:


/*

*/
#include<map>
#include<set>
#include <vector>
#include<stack>
#include<queue>
#include<cmath>
#include<string>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll unsigned long long
#define inf 0x3f3f3f
#define esp 1e-8
#define bug {printf("mmp\n");}
#define mm(a,b) memset(a,b,sizeof(a))
#define T() int test,q=1;scanf("%d",&test); while(test--)
const int maxn=1e4+10;
const double pi=acos(-1.0);
const int N=201;
const int mod=1e9+7;
int b[]={2,3,6,9,11,22,32,78};
int main()
{
    int a;
    cin>>a;
    int index=lower_bound(b,b+8,a)-b;
    cout<<index<<endl;
    return 0;
}

3.upper_bound查找第一个大于某个元素的位置。

使用方法同上

代码同上稍微改改就行了

当两者相减的时候,便可以的得到等于查询值的元素的数的个数

代码:


/*

*/
#include<map>
#include<set>
#include <vector>
#include<stack>
#include<queue>
#include<cmath>
#include<string>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll unsigned long long
#define inf 0x3f3f3f
#define esp 1e-8
#define bug {printf("mmp\n");}
#define mm(a,b) memset(a,b,sizeof(a))
#define T() int test,q=1;scanf("%d",&test); while(test--)
const int maxn=1e4+10;
const double pi=acos(-1.0);
const int N=201;
const int mod=1e9+7;
int b[]={2,3,6,9,11,11,11,22,32,78};
int main()
{
    int a;
    cin>>a;
    int index=upper_bound(b,b+10,a)-lower_bound(b,b+10,a);
    cout<<index<<endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值