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

定义于头文件 <algorithm>

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

返回指向第一个大于给定值的元素的迭代器

std::upper_bound

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

(1)(C++20 前)

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

(C++20 起)

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

(2)(C++20 前)

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

(C++20 起)

返回指向范围 [first, last) 中首个大于 value 的元素的迭代器,或若找不到这种元素则返回 last

范围 [first, last) 必须已相对于表达式 !(value < element) 或 !comp(value, element) 划分,即所有令此表达式为 true 的元素必须前趋所有令此表达式为 false 的元素。完全排序的范围满足此判别标准。

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

参数

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

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

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

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

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

返回值

指向首个大于 value 的元素的迭代器,或若找不到这种元素则为 last

复杂度

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

可能的实现

 版本一

template<class ForwardIt, class T>
ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T& value)
{
    ForwardIt it;
    typename std::iterator_traits<ForwardIt>::difference_type count, step;
    count = std::distance(first,last);
 
    while (count > 0) {
        it = first; 
        step = count / 2; 
        std::advance(it, step);
        if (!(value < *it)) {
            first = ++it;
            count -= step + 1;
        }
        else
            count = step;
    }
    return first;
}

版本二

template<class ForwardIt, class T, class Compare>
ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T& value, Compare comp)
{
    ForwardIt it;
    typename std::iterator_traits<ForwardIt>::difference_type count, step;
    count = std::distance(first,last);
 
    while (count > 0) {
        it = first; 
        step = count / 2;
        std::advance(it, step);
        if (!comp(value, *it)) {
            first = ++it;
            count -= step + 1;
        }
        else
            count = step;
    }
    return 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;
}

template<class ForwardIt, class T, class Compare>
ForwardIt binary_find(ForwardIt first, ForwardIt last, const T& value, Compare comp = {})
{
    // 注意:类型 T 和 Forward 解引用后的类型都必须可隐式转换为
    // 用于 Compare 的 Type1 和 Type2 。
    // 这严格于 lower_bound 要求(见上述)

    first = std::lower_bound(first, last, value, comp);
    return first != last && !comp(value, *first) ? first : last;
}

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);

    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;

    auto lower = std::lower_bound(cells.begin(), cells.end(), *(cells.begin() + 3));
    auto upper = std::upper_bound(cells.begin(), cells.end(), *(cells.begin() + 3));

    std::cout << "cells lower upper:    ";
    std::copy(lower, upper, std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl << std::endl;

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

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

    lower = std::lower_bound(cells.begin(), cells.end(), *(cells.begin() + 3), is_sortfa);
    upper = std::upper_bound(cells.begin(), cells.end(), *(cells.begin() + 3), is_sortfb);

    std::cout << "cells lower upper:    ";
    std::copy(lower, upper, std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl << std::endl;


    auto it = binary_find(cells.cbegin(), cells.cend(), *(cells.begin() + 3), is_sortfa);
    if (it != cells.cend())
    {
        std::cout << *it << " found at index " << std::distance(cells.cbegin(), it);
    }
    std::cout << std::endl ;

    return 0;
}

输出

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值