find()、find_if()、search() 等。值得一提的是,这些函数的底层实现都采用的是顺序查找(逐个遍历)的方式,在某些场景中的执行效率并不高。例如,当指定区域内的数据处于有序状态时,如果想查找某个目标元素,更推荐使用二分查找的方法(相比顺序查找,二分查找的执行效率更高)。

C++ STL标准库中还提供有 lower_bound()、upper_bound()、equal_range() 以及 binary_search() 这 4 个查找函数,它们的底层实现采用的都是二分查找的方式。

本文作者原创,转载请附上文章出处与本文链接。

1 lower_bound()函数

lower_bound() 函数定义在<algorithm>头文件中,其语法格式有 2 种,分别为:

//在 [first, last) 区域内查找不小于 val 的元素
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last,const T& val);
//在 [first, last) 区域内查找第一个不符合 comp 规则的元素
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last,const T& val, Compare comp);

其中,first 和 last 都为正向迭代器,[first, last) 用于指定函数的作用范围;val 用于指定目标元素;comp 用于自定义比较规则,此参数可以接收一个包含 2 个形参(第二个形参值始终为 val)且返回值为 bool 类型的函数,可以是普通函数,也可以是函数对象。

实际上,第一种语法格式也设定有比较规则,只不过此规则无法改变,即使用 < 小于号比较 [first, last) 区域内某些元素和 val 的大小,直至找到一个不小于 val 的元素。这也意味着,如果使用第一种语法格式,则 [first,last) 范围的元素类型必须支持 < 运算符。

此外,该函数还会返回一个正向迭代器,当查找成功时,迭代器指向找到的元素;反之,如果查找失败,迭代器的指向和 last 迭代器相同。

再次强调,该函数仅适用于已排好序的序列。所谓“已排好序”,指的是 [first, last) 区域内所有令 element<val(或者 comp(element,val),其中 element 为指定范围内的元素)成立的元素都位于不成立元素的前面。

1.1 lower_bound() 示例

#include <iostream>     // std::cout
#include <algorithm>    // std::lower_bound
#include <vector>       // std::vector
using namespace std;
//以普通函数的方式定义查找规则
bool mycomp(int i, int j) { return i > j; }
//以函数对象的形式定义查找规则
class mycomp2 {
public:bool operator()(const int& i, const int& j) {cout << "=== i: " << i << " === j: " << j << "\n" ;return i > j;}
};
int main() {int a[5] = { 1,2,3,4,5 };//从 a 数组中找到第一个不小于 3 的元素int* p = lower_bound(a, a + 5, 3);cout << "*p = " << *p << endl;vector<int> myvector{ 4,5,3,1,2 };//根据 mycomp2 规则,从 myvector 容器中找到第一个违背 mycomp2 规则的元素vector<int>::iterator iter = lower_bound(myvector.begin(), myvector.end(), 3, mycomp2());cout << "*iter = " << *iter;return 0;
}

1.2 底层实现

    template <class ForwardIterator, class T>ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val){ForwardIterator it;iterator_traits<ForwardIterator>::difference_type count, step;count = distance(first,last);while (count>0){it = first; step=count/2; advance (it,step);if (*it<val) {  //或者 if (comp(*it,val)),对应第 2 种语法格式first=++it;count-=step+1;}else count=step;}return first;}

2 upper_bound()函数

upper_bound() 函数定义在<algorithm>头文件中,用于在指定范围内查找大于目标值的第一个元素。该函数的语法格式有 2 种,分别是:

//查找[first, last)区域中第一个大于 val 的元素。
ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last,const T& val);
//查找[first, last)区域中第一个不符合 comp 规则的元素
ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last,const T& val, Compare comp);

其中,first 和 last 都为正向迭代器,[first, last) 用于指定该函数的作用范围;val 用于执行目标值;comp 作用自定义查找规则,此参数可接收一个包含 2 个形参(第一个形参值始终为 val)且返回值为 bool 类型的函数,可以是普通函数,也可以是函数对象。

实际上,第一种语法格式也设定有比较规则,即使用 < 小于号比较 [first, last) 区域内某些元素和 val 的大小,直至找到一个大于 val 的元素,只不过此规则无法改变。这也意味着,如果使用第一种语法格式,则 [first,last) 范围的元素类型必须支持 < 运算符。

同时,该函数会返回一个正向迭代器,当查找成功时,迭代器指向找到的元素;反之,如果查找失败,迭代器的指向和 last 迭代器相同。

另外,由于 upper_bound() 底层实现采用的是二分查找的方式,因此该函数仅适用于“已排好序”的序列。注意,这里所说的“已排好序”,并不要求数据完全按照某个排序规则进行升序或降序排序,而仅仅要求 [first, last) 区域内所有令 element<val(或者 comp(val, element)成立的元素都位于不成立元素的前面(其中 element 为指定范围内的元素)。

2.1 upper_bound()示例

#include <iostream>     // std::cout
#include <algorithm>    // std::upper_bound
#include <vector>       // std::vector
using namespace std;
//以普通函数的方式定义查找规则
bool mycomp(int i, int j) { return i > j; }
//以函数对象的形式定义查找规则
class mycomp2 {
public:bool operator()(const int& i, const int& j) {cout << "=== i: " << i << " === j: " << j << "\n";return i > j;}
};
int main() {int a[5] = { 1,2,3,4,5 };//从 a 数组中找到第一个大于 3 的元素int* p = upper_bound(a, a + 5, 3);cout << "*p = " << *p << endl;vector<int> myvector{ 4,5,3,1,2 };//根据 mycomp2 规则,从 myvector 容器中找到第一个违背 mycomp2 规则的元素vector<int>::iterator iter = upper_bound(myvector.begin(), myvector.end(), 3, mycomp2());cout << "*iter = " << *iter;return 0;
}

此程序中演示了 upper_bound() 函数的 2 种适用场景,其中 a[5] 数组中存储的为升序序列;而 myvector 容器中存储的序列虽然整体是乱序的,但对于目标元素 3 来说,所有符合 mycomp2(3, element) 规则的元素都位于其左侧,不符合的元素都位于其右侧,因此 upper_bound() 函数仍可正常执行。

2.2 底层实现

    template <class ForwardIterator, class T>ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last, const T& val){ForwardIterator it;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))  // 或者 if (!comp(val,*it)), 对应第二种语法格式{ first=++it; count-=step+1;  }else count=step;}return first;}

3 equel_range()函数

equel_range() 函数定义在<algorithm>头文件中,用于在指定范围内查找等于目标值的所有元素。

值得一提的是,当指定范围内的数据支持用 < 小于运算符直接做比较时,可以使用如下格式的 equel_range() 函数:

//找到 [first, last) 范围中所有等于 val 的元素
pair<ForwardIterator,ForwardIterator> equal_range (ForwardIterator first, ForwardIterator last, const T& val);

如果指定范围内的数据为自定义的类型(用结构体或类),就需要自定义比较规则,这种情况下可以使用如下格式的 equel_range() 函数:

//找到 [first, last) 范围内所有等于 val 的元素
pair<ForwardIterator,ForwardIterator> equal_range (ForwardIterator first, ForwardIterator last, const T& val, Compare comp);

以上 2 种格式中,first 和 last 都为正向迭代器,[first, last) 用于指定该函数的作用范围;val 用于指定目标值;comp 用于指定比较规则,此参数可接收一个包含 2 个形参(第二个形参值始终为 val)且返回值为 bool 类型的函数,可以是普通函数,也可以是函数对象。

同时,该函数会返回一个 pair 类型值,其包含 2 个正向迭代器。当查找成功时:

  1. 第 1 个迭代器指向的是 [first, last) 区域中第一个等于 val 的元素;
  2. 第 2 个迭代器指向的是 [first, last) 区域中第一个大于 val 的元素。

反之如果查找失败,则这 2 个迭代器要么都指向大于 val 的第一个元素(如果有),要么都和 last 迭代器指向相同。

需要注意的是,由于 equel_range() 底层实现采用的是二分查找的方式,因此该函数仅适用于“已排好序”的序列。所谓“已排好序”,并不是要求 [first, last) 区域内的数据严格按照某个排序规则进行升序或降序排序,只要满足“所有令 element<val(或者 comp(element,val)成立的元素都位于不成立元素的前面(其中 element 为指定范围内的元素)”即可。

3.1 equel_range()示例


#include <iostream>     // std::cout
#include <algorithm>    // std::equal_range
#include <vector>       // std::vector
using namespace std;
//以普通函数的方式定义查找规则
bool mycomp(int i, int j) { return i > j; }
//以函数对象的形式定义查找规则
class mycomp2 {
public:bool operator()(const int& i, const int& j) {cout << "=== i: " << i << " === j: " << j << "\n";return i > j;}
};
int main() {int a[9] = { 1,2,3,4,4,4,5,6,7 };//从 a 数组中找到所有的元素 4pair<int*, int*> range = equal_range(a, a + 9, 4);cout << "a[9]:";for (int* p = range.first; p < range.second; ++p) {cout << *p << " ";}vector<int>myvector{ 7,8,5,4,3,3,3,3,2,1 };pair<vector<int>::iterator, vector<int>::iterator> range2;//在 myvector 容器中找到所有的元素 3range2 = equal_range(myvector.begin(), myvector.end(), 3, mycomp2());cout << "\nmyvector:";for (auto it = range2.first; it != range2.second; ++it) {cout << *it << " ";}return 0;
}

此程序中演示了 equal_range() 函数的 2 种适用场景,其中 a[9] 数组中存储的为升序序列;而 myvector 容器中存储的序列虽然整体是乱序的,但对于目标元素 3 来说,所有符合 mycomp2(element, 3) 规则的元素都位于其左侧,不符合的元素都位于其右侧,因此 equal_range() 函数仍可正常执行。

实际上,equel_range() 函数的功能完全可以看做是 lower_bound() 和 upper_bound() 函数的合体。C++ STL标准库给出了 equel_range() 函数底层实现的参考代码(如下所示),感兴趣的读者可自行研究,这里不再赘述:

3.2 equel_range() 底层实现


#include <iostream>     // std::cout
#include <algorithm>    // std::equal_range
#include <vector>       // std::vector
using namespace std;
//以普通函数的方式定义查找规则
bool mycomp(int i, int j) { return i > j; }
//以函数对象的形式定义查找规则
class mycomp2 {
public:bool operator()(const int& i, const int& j) {cout << "=== i: " << i << " === j: " << j << "\n";return i > j;}
};
int main() {int a[9] = { 1,2,3,4,4,4,5,6,7 };//从 a 数组中找到所有的元素 4pair<int*, int*> range = equal_range(a, a + 9, 4);cout << "a[9]:";for (int* p = range.first; p < range.second; ++p) {cout << *p << " ";}vector<int>myvector{ 7,8,5,4,3,3,3,3,2,1 };pair<vector<int>::iterator, vector<int>::iterator> range2;//在 myvector 容器中找到所有的元素 3range2 = equal_range(myvector.begin(), myvector.end(), 3, mycomp2());cout << "\nmyvector:";for (auto it = range2.first; it != range2.second; ++it) {cout << *it << " ";}return 0;
}

4 binary_search()函数

该函数有 2 种语法格式,分别为:

//查找 [first, last) 区域内是否包含 val
bool binary_search (ForwardIterator first, ForwardIterator last,const T& val);
//根据 comp 指定的规则,查找 [first, last) 区域内是否包含 val
bool binary_search (ForwardIterator first, ForwardIterator last,const T& val, Compare comp);

其中,first 和 last 都为正向迭代器,[first, last) 用于指定该函数的作用范围;val 用于指定要查找的目标值;comp 用于自定义查找规则,此参数可接收一个包含 2 个形参(第一个形参值为 val)且返回值为 bool 类型的函数,可以是普通函数,也可以是函数对象。

同时,该函数会返回一个 bool 类型值,如果 binary_search() 函数在 [first, last) 区域内成功找到和 val 相等的元素,则返回 true;反之则返回 false。

需要注意的是,由于 binary_search() 底层实现采用的是二分查找的方式,因此该函数仅适用于“已排好序”的序列。所谓“已排好序”,并不是要求 [first, last) 区域内的数据严格按照某个排序规则进行升序或降序排序,只要满足“所有令 element<val(或者 comp(val, element)成立的元素都位于不成立元素的前面(其中 element 为指定范围内的元素)”即可。

4.1 binary_search()示例

#include <iostream>     // std::cout
#include <algorithm>    // std::binary_search
#include <vector>       // std::vector
using namespace std;
//以普通函数的方式定义查找规则
bool mycomp(int i, int j) { return i > j; }
//以函数对象的形式定义查找规则
class mycomp2 {
public:bool operator()(const int& i, const int& j) {cout << "=== i: " << i << " === j: " << j << "\n";return i > j;}
};
int main() {int a[7] = { 1,2,3,4,5,6,7 };//从 a 数组中查找元素 4bool haselem = binary_search(a, a + 9, 4);cout << "haselem:" << haselem << endl;vector<int>myvector{ 4,5,3,1,2 };//从 myvector 容器查找元素 3bool haselem2 = binary_search(myvector.begin(), myvector.end(), 3, mycomp2());cout << "haselem2:" << haselem2;return 0;
}

此程序中演示了 binary_search() 函数的 2 种适用场景,其中 a[7] 数组中存储的为升序序列;而 myvector 容器中存储的序列虽然整体是乱序的,但对于目标元素 3 来说,所有符合 mycomp2(element, 3) 规则的元素都位于其左侧,不符合的元素都位于其右侧,因此 binary_search() 函数仍可正常执行。

4.2 底层实现

    //第一种语法格式的实现template <class ForwardIterator, class T>bool binary_search (ForwardIterator first, ForwardIterator last, const T& val){first = std::lower_bound(first,last,val);return (first!=last && !(val<*first));}//第二种语法格式的底层实现template<class ForwardIt, class T, class Compare>bool binary_search(ForwardIt first, ForwardIt last, const T& val, Compare comp){first = std::lower_bound(first, last, val, comp);return (!(first == last) && !(comp(val, *first)));}

C++ lower_bound() upper_bound() 函数用法详解(深入了解,一文学会)相关推荐

  1. C++ search()函数用法详解(深入了解,一文学会)

    find_end() 函数用于在序列 A 中查找序列 B 最后一次出现的位置.那么,如果想知道序列 B 在序列 A 中第一次出现的位置,该如何实现呢?可以借助 search() 函数. search( ...

  2. C++ reverse()函数用法详解(深入了解,一文学会)

    reverse_copy() 算法可以将源序列复制到目的序列中,目的序列中的元素是逆序的.定义源序列的前两个迭代器参数必须是双向迭代器.目的序列由第三个参数指定,它是目的序列的开始迭代器,也是一个输出 ...

  3. ROW_NUMBER() OVER()函数用法详解 (分组排序 例子多)

    ROW_NUMBER() OVER()函数用法详解 (分组排序 例子多) https://blog.csdn.net/qq_25221835/article/details/82762416 post ...

  4. C++中substr()函数用法详解

    C++中substr()函数用法详解 原型: string substr (size_t pos = 0, size_t len = npos) const; 返回一个新构造的string对象,其值初 ...

  5. LayoutInflater的inflate函数用法详解

    LayoutInflater的inflate函数用法详解 LayoutInflater作用是将layout的xml布局文件实例化为View类对象. 获取LayoutInflater的方法有如下三种: ...

  6. c++ memset 语言_C++中memset函数用法详解

    本文实例讲述了C++中memset函数用法.分享给大家供大家参考,具体如下: 功 能: 将s所指向的某一块内存中的每个字节的内容全部设置为ch指定的ASCII值,块的大小由第三个参数指定,这个函数通常 ...

  7. mysql: union / union all / 自定义函数用法详解

    mysql: union / union all http://www.cnblogs.com/wangyayun/p/6133540.html mysql:自定义函数用法详解 http://www. ...

  8. python中mat函数_Python中flatten( )函数及函数用法详解

    flatten()函数用法 flatten是numpy.ndarray.flatten的一个函数,即返回一个一维数组. flatten只能适用于numpy对象,即array或者mat,普通的list列 ...

  9. ROW_NUMBER() OVER()函数用法详解

    今天同事问了一个关于插入表的问题,对象:被插入表sys_equi_disorg   A  , 查询表sys_equi_dict   B 因为A表的ID不是自增的,并且不能更改表结构,主键默认值还是0, ...

最新文章

  1. php上传图片到文件夹,2018.09.14PHP获取页面上传的图片存到指定文件夹再存到数据库中...
  2. 遇到Request header is too large,你们是如何解决的?
  3. linux dry run,dry run
  4. 章节六、2-异常---运行时异常
  5. 学习心得体会、备忘录整理
  6. 是否显示展开_Creo7.0教程之绝对精度对钣金件展开的作用详解
  7. java演练0920 我们9203班 02 随机点名功能实现
  8. 使用fiddler脚本修改x-frame-options
  9. 阿里云短信服务的使用(创建,测试笔记)
  10. Unity3D人体18节点骨骼动态简单点线模型的建立
  11. html语言设置表格颜色,HTML怎么设置表格单元格颜色
  12. 研发团队管理--向上沟通
  13. win10没有远程网络网关_加强远程工作网络安全的10种方法
  14. c语言 获取文件修改时间,C语言中用于修改文件的存取时间的函数使用
  15. vue中click无效问题
  16. 初中数学抽象教学的案例_初中数学教学案例及反思
  17. Data truncation: Incorrect datetime value: ‘XXXX‘
  18. 阿里巴巴离职DBA_35岁总结的职业生涯
  19. 软件开发中,站立会议的必要性
  20. php获取股市交易日,个股交易日一年多少天?股市交易时间规定

热门文章

  1. 《JavaScript 闯关记》
  2. 递归牛顿欧拉(正/逆)动力学仿真
  3. 网卡属性中的巨帧、巨型帧、Jumbo Frame
  4. Spring中的切入点表达式写法
  5. revit常用出图软件实现【本层三维】,生成本楼层标高范围
  6. 图灵奖得主Yoshua Bengio:用因果打开AI的黑盒
  7. 【100个 Unity实用技能】☀️ | Unity中 检查当前设备网络状态 的几种方法整理
  8. 夏季晒黑如何变白?店湾妹教你几招,皮肤回归白嫩
  9. html5 canvas详解 pdf,html5 canvas教程 pdf
  10. 机器学习和深度学习资料