STL中二分查找函数

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    int a[12] = {1,6,31,66,67,68,69,70,71,73,76,79};
    int c[12] = {79,76,73,71,70,69,68,67,66,31,6,1};
    vector<int> b;
    b.push_back(1);
    b.push_back(6);
    b.push_back(31);
    b.push_back(66);
    b.push_back(67);
    b.push_back(68);
    b.push_back(69);
    b.push_back(70);
    b.push_back(71);
    b.push_back(73);
    b.push_back(76);
    b.push_back(79);
    int n;

binary_search(b.begin(),b.end(),n)//返回得是bool值,也适用于数组,用于判断有没有找到

if(binary_search(a,a+12,n))printf("find %d\n",n);
        else printf("%d is not in array\n");
        if(binary_search(b.begin(),b.end(),n))printf("find %d\n",n);
        else printf("%d is not in array\n",n);*/
        >>>
        66
        find 66
        find 66
        99
        6422256 is not in array
        99 is not in array
        

lower_bound(b.begin(),b.end(),n);//返回得是迭代器,也适用于数组(用对应类型得指针接着就好),用于查找第一个不小于n得值得位置(p-1就是第一个比n小的索引了)

int *p;
        vector<int>::iterator it;
        p = lower_bound(a,a+12,n);
        if(p != a + 12)
        {
                    printf("The first num which is bigger(or equal) than %d is %d,index is : %d\n",n,*p,(p - a));
        }
        else printf("Not found!\n");

        it = lower_bound(b.begin(),b.end(),n);
        if(it != b.end())
        {
        printf("The first num which is bigger(or equal) than %d is %d,index is : %d\n",n,*it,distance(b.begin(),it));
        }
        else printf("Not found!\n");
        >>>
        6
            The first num which is bigger(or equal) than 6 is 6,index is : 1
            The first num which is bigger(or equal) than 6 is 6,index is : 1
            1
            The first num which is bigger(or equal) than 1 is 1,index is : 0
            The first num which is bigger(or equal) than 1 is 1,index is : 0
            0
            The first num which is bigger(or equal) than 0 is 1,index is : 0
            The first num which is bigger(or equal) than 0 is 1,index is : 0
            99
            Not found!
            Not found!
        

upper_bound(b.begin(),b.end(),n);//返回得是迭代器,也适用于数组(用对应类型得指针接着就好),用于查找第大于n得值得位置

       int *p;
        vector<int>::iterator it;
        p = upper_bound(a,a+12,n);
        if(p != a+12)
        {
            printf("The first num which is bigger than %d is %d,index is : %d\n",n,*p,(p - a));
        }
        else printf("Not found!\n");

        it = upper_bound(b.begin(),b.end(),n);
        if(it != b.end())
        {
            printf("The first num which is bigger than %d is %d,index is : %d\n",n,*it,distance(b.begin(),it));
        }
        else printf("Not found!\n");*/
        >>>
        6
    The first num which is bigger than 6 is 31,index is : 2
    The first num which is bigger than 6 is 31,index is : 2
    78
    The first num which is bigger than 78 is 79,index is : 11
    The first num which is bigger than 78 is 79,index is : 11
    79
    Not found!
    Not found!
      

对于lower_bound & upper_bound()还有一个第四个参数greater<type>(),他会把不小于变为不大于得查找,把大于变为小于得查找,但是相反,他要求得顺序不是递增,而是递减!!!

int *p = lower_bound(c,c+12,n,greater<int>());//传入第四个参数,查找第一个小于等于n得值
    if(p != c+12)
    {
        printf("The first num which is smaller(or equal) than %d is %d,index is : %d\n",n,*p,(p - c));
    }
    else printf("Not found!\n");
    >>>
    6
    The first num which is smaller(or equal) than 6 is 6,index is : 10
    5
    The first num which is smaller(or equal) than 5 is 1,index is : 11
    0
    Not found!
    


忘了提一下distence函数他是用于迭代器得用于计算他们之间的距离~~~(注意好传值的先后顺序)

### STL二分查找的源码实现 STL中的二分查找函数包括`binary_search`、`lower_bound`、`upper_bound`和`equal_range`,这些函数均基于二分查找算法实现。以下是这些函数的基本实现原理及其源码剖析。 #### 1. `binary_search` `binary_search`试图在已排序的`[first, last)`区间内查找元素`value`是否存在。如果存在,则返回`true`;否则返回`false`。其核心逻辑是通过比较中间值与目标值的关系逐步缩小搜索范围[^3]。 ```cpp template <class ForwardIterator, class T> bool binary_search(ForwardIterator first, ForwardIterator last, const T& val) { while (first != last) { ForwardIterator mid = first + (last - first) / 2; if (*mid < val) { first = mid + 1; } else if (val < *mid) { last = mid; } else { return true; // 找到相等的值 } } return false; // 没有找到 } ``` #### 2. `lower_bound` `lower_bound`在`[first, last)`区间内寻找第一个大于或等于`val`的元素位置。如果所有元素都小于`val`,则返回`last`的位置。其核心思想是不断调整左右边界,直到找到满足条件的位置[^4]。 ```cpp template <class ForwardIterator, class T> ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& val) { ForwardIterator it; typename std::iterator_traits<ForwardIterator>::difference_type count, step; count = std::distance(first, last); while (count > 0) { it = first; step = count / 2; std::advance(it, step); if (*it < val) { first = ++it; count -= step + 1; } else { count = step; } } return first; } ``` #### 3. `upper_bound` `upper_bound`在`[first, last)`区间内寻找第一个大于`val`的元素位置。如果所有元素都不大于`val`,则返回`last`的位置。其实现方式与`lower_bound`类似,但比较条件稍有不同[^2]。 ```cpp template <class ForwardIterator, class T> ForwardIterator upper_bound(ForwardIterator first, ForwardIterator last, const T& val) { ForwardIterator it; typename std::iterator_traits<ForwardIterator>::difference_type count, step; count = std::distance(first, last); while (count > 0) { it = first; step = count / 2; std::advance(it, step); if (!(val < *it)) { // 注意这里是 !(val < *it) first = ++it; count -= step + 1; } else { count = step; } } return first; } ``` #### 4. `equal_range` `equal_range`结合了`lower_bound`和`upper_bound`的功能,返回一个包含两个迭代器的`pair`,分别表示`lower_bound`和`upper_bound`的结果[^5]。 ```cpp template <class ForwardIterator, class T> std::pair<ForwardIterator, ForwardIterator> equal_range(ForwardIterator first, ForwardIterator last, const T& val) { ForwardIterator lb = lower_bound(first, last, val); return std::make_pair(lb, upper_bound(lb, last, val)); } ``` ### 总结 上述代码展示了STL二分查找相关函数的核心实现逻辑。这些函数均基于二分查找算法,通过逐步缩小搜索范围来高效地完成任务。此外,需要注意的是,这些函数要求输入的序列必须是有序的,否则结果可能不正确[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值