美文网首页
C++ STL binary_search 函数说明

C++ STL binary_search 函数说明

作者: book_02 | 来源:发表于2020-06-06 21:48 被阅读0次

1. 说明

用二分查找的方法检查指定值val是否在范围[first,last)内存在

找到了,返回 true ; 没找到,返回 false 。

注意:

  1. 范围[first,last)内的元素要求是有序的。

函数签名如下:

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

2. 头文件

#include <algorithm>

3. 例子


#include <iostream>
#include <vector>
#include <algorithm>


int main(int argc, char **argv) 
{  
    std::vector<int> nums = { 1, 3, 4, 5, 9 };

    std::sort(nums.begin(), nums.end());          

    std::cout << std::binary_search(nums.begin(), nums.end(), 2) << endl;
    std::cout << std::binary_search(nums.begin(), nums.end(), 3) << endl;
  
    return 0;
}

结果:

0
1

4. 参考

https://en.cppreference.com/w/cpp/algorithm/binary_search

相关文章

  • C++ STL binary_search 函数说明

    1. 说明 用二分查找的方法检查指定值val是否在范围[first,last)内存在 找到了,返回 true ; ...

  • C++ STL transform 函数说明

    说明 简而言之,transform是用来做转换的。转换有两种:一元转换和二元转换。 一元转换是对容器给定范围内的每...

  • C++ STL iota 函数说明

    说明 iota用一个从value递增的数列给[first, last)的容器赋值等效于 C++11 才引入,之前版...

  • C++库

    标准库C++标准库,包括了STL容器,算法和函数等。C++ Standard Library:是一系列类和函数的集...

  • GeekBand C++ STL与泛型编程 第一周学习笔记

    STL概述 C++标准库包含STL和一些其他内容 STL有六大组件: 容器,分配器,算法,迭代器,适配器,仿函数 ...

  • [资源]C++ 程序员必收藏

    C++ 资源大全中文版 标准库 C++标准库,包括了STL容器,算法和函数等。 C++ Standard Libr...

  • 读书笔记17.06.03

    C++ STL:Listlist是C++标准模版库(STL,Standard Template Library)中...

  • [C++] STL 容器

    参考:[C++] STL 容器 (一) - 基本介紹[C++] STL 容器 (二) - Iterator 部分示例:

  • C++后端开发的踩坑整理

    C++开发的一些经验和踩坑整理 STL相关的坑 1. std::sort()函数要求严格弱序 STL文档中要求so...

  • C++ STL back_inserter 函数说明

    说明 back_inserter用于在末尾插入元素。实现方法是构造一个迭代器,这个迭代器可以在容器末尾添加元素。这...

网友评论

      本文标题:C++ STL binary_search 函数说明

      本文链接:https://www.haomeiwen.com/subject/affgzhtx.html