算法介绍
lower_bound、upper_bound、binary_search算法都定义在头文件<algorithm.h>中,都基于“二分搜索”实现。
使用条件:数列有序。对于输入的容器类型,不能是set、map、list这种非连续性的容器,对于set、map、list它们都有自己的内置lower_bound、upper_bound函数。
lower_bound
lower_bound(起始地址(或迭代器),结束地址(或迭代器),target)
返回值:第一个不小于target的元素出现的位置(迭代器)。如果容器中没有不小于 target的元素,则返回结束地址(迭代器)。
upper_bound
upper_bound(起始地址(或迭代器),结束地址(或迭代器),target)
返回值:第一个大于target的元素出现的位置(迭代器)。如果容器中没有大于 target的元素,则返回结束地址(迭代器)。
binary_search
upper_bound(起始地址(或迭代器),结束地址(或迭代器),target)
返回值:bool类型,表示target是否在容器中。
测试用例
#include <iostream>
#

本文介绍了C++ STL中的lower_bound、upper_bound和binary_search三个算法,它们基于二分搜索并在有序容器中查找元素。lower_bound返回第一个不小于目标值的元素位置,upper_bound返回第一个大于目标值的元素位置,而binary_search则判断目标值是否在容器中。
最低0.47元/天 解锁文章
1657

被折叠的 条评论
为什么被折叠?



