函数原型
//不带谓词 template_NODISCARD inline pair<_FwdIt, _FwdIt> equal_range(_FwdIt _First, _FwdIt _Last, const _Ty& _Val) //带谓词 template _NODISCARD inline bool binary_search(_FwdIt _First, _FwdIt _Last, const _Ty& _Val, _Pr _Pred)
查找指定区域内是否包含某个目标元素。如果找到第三个参数,这个算法会返回布尔值 true,否则返回 false。
参数
first 和 last 都为正向迭代器,[first, last) 用于指定该函数的查找范围;
val 给定值;
pr自定义规则,此参数可接收一个包含 2 个形参(第二个形参值始终为 val)且返回值为 bool 类型的函数,可以是普通函数,也可以是函数对象。
不带谓词
#include带谓词#include #include #include #include int main() { std::vector bb{ 1, 2, 3, 4, 3, 5, 2, 3, 10, 23, 55 }; std::sort(std::begin(bb), std::end(bb)); std::cout << "sort the integer: "; std::for_each(std::begin(bb), std::end(bb), [](int value) {std::cout << value << " "; }); std::cout << std::endl; bool rtn = std::binary_search(std::begin(bb), std::end(bb), 3); if (rtn) { std::cout << "find the element: " << rtn << std::endl; } return -1; } //输出 sort the integer: 1 2 2 3 3 3 4 5 10 23 55 find the element: 1



