zoukankan      html  css  js  c++  java
  • C++ Essentials 之 lower_bound 和 upper_bound 的比较函数格式不同

    第一次注意到这个问题。

    cppreference 上的条目:
    lower_bound
    upper_bound

    C++17 草案 N4659

    lower_bound

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

    Requires: The elements e of [first, last) shall be partitioned with respect to the expression e < value or comp(e, value).

    Returns: The furthermost iterator i in the range [first, last] such that for every iterator j in the
    range [first, i) the following corresponding conditions hold: *j < value or comp(*j, value) != false.

    upper_bound

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

    Requires: The elements e of [first, last) shall be partitioned with respect to the expression !(value < e) or !comp(value, e).

    Returns: The furthermost iterator i in the range [first, last] such that for every iterator j in the
    range [first, i) the following corresponding conditions hold: !(value < *j) or comp(value, *j) == false.

    分析

    为何如此设计?

    这是有原因的。
    lower_boundupper_bound 的比较函数都只能判定严格偏序。也就是说 comp(value, j) 只能判定 value < *j,而不能判定 value == *j*j < value

    如果 upper_bound 的比较函数只能判定 *j < value,那么对于一个有序的全序序列,它就无法二分找出大于 value 的第一个元素所在的位置(iterator)。原因在于对于任意 iterator j,判定 *j > value 根本不可能。

  • 相关阅读:
    移动端 提交按钮呗软键盘挤上去的问题解决
    jenkins创建项目API踩坑记
    backstage使用笔记(2)- 跨域代理设置
    backstage使用笔记(1)- 项目的搭建和插件的创建
    什么是强缓存,什么是协商缓存?
    关于antd英文文案切换为中文
    记解决遇到自己电脑看线上项目没问题,别的同事电脑看线上项目有问题的疑难杂症
    vue.js组件传值
    Vue.js组件
    关于Object.keys()和for in的区别
  • 原文地址:https://www.cnblogs.com/Patt/p/9914032.html
Copyright © 2011-2022 走看看