STL_二分_【binary_search、upper_bound、lower_bound】

这篇博客介绍了STL中关于二分查找的三个函数:lower_bound、upper_bound和binary_search。这些函数适用于有序区间,lower_bound返回第一个大于等于给定值的位置,upper_bound返回第一个大于给定值的位置,而binary_search则检查序列中是否存在指定值。使用二分查找前,需确保序列已按升序排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于STL中的二分查找

这里写图片描述
(1)STL中关于二分查找的函数有三个:lower_bound 、upper_bound 、binary_search
—— 这三个函数都运用于有序区间(当然这也是运用二分查找的前提)
(2)ForwardIter lower_bound(ForwardIter first, ForwardIter last,const _Tp& val)
算法返回一个非递减序列[first, last)中的第一个大于等于值val的位置;
(3)ForwardIter upper_bound(ForwardIter first, ForwardIter last, const _Tp& val)
算法返回一个非递减序列[first, last)中的第一个大于值val的位置。
(4)binary_search(ForwardIter first, ForwardIter last, const _Tp& val) 返回是否存在val

大家都知道,二分查找是在排序后的基础上来对其进行查找操作。
所以在使用binary_search的时候,需要对将要查找的容器进行排序。
特别强调:排序的必须是要从小到大

下面就通过简单易懂的代码对其讲解

#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
vector <int> V;
int a[10];
set <int> S;
struct Node//结构体定义以及运算符重载
{
    int x,y;
    bool operator<(const Node &rhs)const
    {
        if(x == rhs.x)
            return y < rhs.y;
        else
            return x < rhs.x;
    }
}nodes[10];


int main()
{
    ///数组
    for(int i = 0; i < 10; ++ i)
        a[i] = i * 2;
    int p, q;
    sort(a, a + 10);
    p = lower_bound(a, a + 10, 4) - a;
    q = upper_bound(a, a + 10, 4) - a;
    cout << p << endl << q << endl;
    if(binary_search(a, a + 10, 12))
        cout << "array : Yes" << endl;
    else
        cout << "array :No" << endl;
    ///vector
    V.push_back(2);
    V.push_back(3);
    V.push_back(1);
    sort(V.begin(), V.end());//对vector 的排序
    if(binary_search(V.begin(), V.end(), 5)) // 对vector进行二分查找
        cout << "vector : Yes" << endl;
    else
        cout << "vector : No" << endl;
    /// set
    for(int i = 0; i < 10; ++ i)
        S.insert(i);

    set <int> :: iterator itb = S.begin();
    set <int> :: iterator ite = S.end();
    if(binary_search(itb, ite, 1)) // 对vector进行二分查找
        cout << "set : Yes" << endl;
    else
        cout << "set : No" << endl;
    /*
    在对结构体进行二分操作之前,肯定需要先对其排序。
    对结构体排序就需要用到运算符重载,对结构体中的<进行重载,
    排序可以直接用sort排序,或者是定义一个结构体类型的set,set会对其去重排序。
    然后就可以使用二分查找了。
    */
    for(int i = 0; i < 10; ++ i)
        nodes[i].x = i, nodes[i].y = i;
    sort(nodes, nodes + 10);
    Node tmp;
    tmp.x = 5, tmp.y = 5;
    if(binary_search(nodes, nodes + 10, tmp))
        cout << "struct : Yes" << endl;
    else
        cout << "struct : No" << endl;

    p = lower_bound(nodes, nodes + 10, tmp) - nodes;
    q = upper_bound(nodes, nodes + 10, tmp) - nodes;
    cout << p << endl << q << endl;
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值