C++11标准模板(STL)- 算法 - 二分搜索操作(在已排序范围上) (std::binary_search)

定义于头文件 <algorithm>

算法库提供大量用途的函数(例如查找、排序、计数、操作),它们在元素范围上操作。注意范围定义为 [first, last) ,其中 last 指代要查询或修改的最后元素的后一个元素。

确定元素是否存在于某范围中

std::binary_search

template< class ForwardIt, class T >
bool binary_search( ForwardIt first, ForwardIt last, const T& value );

(1)(C++20 前)

template< class ForwardIt, class T >
constexpr bool binary_search( ForwardIt first, ForwardIt last, const T& value );

(C++20 起)

template< class ForwardIt, class T, class Compare >
bool binary_search( ForwardIt first, ForwardIt last, const T& value, Compare comp );

(2)(C++20 前)

template< class ForwardIt, class T, class Compare >
constexpr bool binary_search( ForwardIt first, ForwardIt last, const T& value, Compare comp );

(C++20 起)

检查等价于 value 的元素是否出现于范围 [first, last) 中。

对于要成功的 std::binary_search ,范围 [first, last) 必须至少相对于 value 部分有序,即它必须满足下列所有要求:

  • 已相对 element < value 或 comp(element, value) 划分
  • 已相对 !(value < element) 或 !comp(value, element) 划分(即所有令此表达式为 true 的元素必须前趋所有令此表达式为 false 的元素)
  • 对于所有元素,若 element < value 或 comp(element, value) 为 true ,则 !(value < element) 或 !comp(value, element) 亦为 true

完全排序的范围满足这些判别标准。

第一版本用 operator< 比较元素,第二版本用给定的比较函数 comp

参数

first, last-要检验的元素范围
value-要与元素比较的值
comp-若第一参数小于(即先序于)第二个则返回 ​true 的二元谓词。

谓词函数的签名应等价于如下:

 bool pred(const Type1 &a, const Type2 &b);

虽然签名不必有 const & ,函数也不能修改传递给它的对象,而且必须接受(可为 const 的)类型 Type1Type2 的值,无关乎值类别(从而不允许 Type1 & ,亦不允许 Type1 ,除非 Type1 的移动等价于复制 (C++11 起))。
类型 Type1 必须使得 ForwardIt 类型的对象能在解引用后隐式转换到 Type1 。类型 Type2 必须使得 T 类型的对象能隐式转换到 Type2 。 ​

类型要求
- ForwardIt 必须满足遗留向前迭代器 (LegacyForwardIterator) 的要求。
- Compare 必须满足二元谓词 (BinaryPredicate) 的要求。不要求满足 比较 (Compare) 。

返回值

若找到等于 value 的元素则为 true ,否则为 false 。

复杂度

进行的比较次数与 firstlast 间的距离成对数(至多 log
2(last - first) + O(1) 次比较)。然而,对于非遗留随机访问迭代器 (LegacyRandomAccessIterator) ,迭代次自增次数为线性。

可能的实现

版本一

template<class ForwardIt, class T>
bool binary_search(ForwardIt first, ForwardIt last, const T& value)
{
    first = std::lower_bound(first, last, value);
    return (!(first == last) && !(value < *first));
}

版本二

template<class ForwardIt, class T, class Compare>
bool binary_search(ForwardIt first, ForwardIt last, const T& value, Compare comp)
{
    first = std::lower_bound(first, last, value, comp);
    return (!(first == last) && !(comp(value, *first)));
}

调用示例

#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <iterator>
#include <time.h>

using namespace std;

struct Cell
{
    int x;
    int y;

    Cell &operator +=(const Cell &cell)
    {
        x += cell.x;
        y += cell.y;
        return *this;
    }

    bool operator <(const Cell &cell) const
    {
        if (x == cell.x)
        {
            return y < cell.y;
        }
        else
        {
            return x < cell.x;
        }
    }
};

std::ostream &operator<<(std::ostream &os, const Cell &cell)
{
    os << "{" << cell.x << "," << cell.y << "}";
    return os;
}

int main()
{
    srand((unsigned)time(NULL));;

    std::cout.setf(std::ios_base::boolalpha);

    auto func1 = []()
    {
        int n = std::rand() % 10 + 100;
        Cell cell{n, n};
        return cell;
    };

    vector<Cell> cells(8);
    std::generate(cells.begin(), cells.end(), func1);

    vector<Cell> fcells(3);
    std::generate(fcells.begin(), fcells.end(), func1);

    std::sort(cells.begin(), cells.end());
    std::cout << "cells :       ";
    std::copy(cells.begin(), cells.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl << std::endl;

    for (const Cell &cell : fcells)
    {
        bool b = std::binary_search(cells.begin(), cells.end(), cell);
        std::cout << "cell: " << cell << (b ? " found " : " not found ") << std::endl;
    }

    std::cout << std::endl << std::endl;

    auto func2 = [](const Cell & a, const Cell & b)
    {
        if (a.x == b.x)
        {
            return a.y < b.y;
        }
        return a.x < b.x;
    };

    std::generate(cells.begin(), cells.end(), func1);
    std::generate(fcells.begin(), fcells.end(), func1);

    std::sort(cells.begin(), cells.end());
    std::cout << "cells :       ";
    std::copy(cells.begin(), cells.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl << std::endl;

    for (const Cell &cell : fcells)
    {
        bool b = std::binary_search(cells.begin(), cells.end(), cell, func2);
        std::cout << "cell: " << cell << (b ? " found " : " not found ") << std::endl;
    }

    return 0;
}

输出

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值