zoukankan      html  css  js  c++  java
  • std::binary_serach, std::upper_bound以及std::lower_bound

    c++二分查找的用法

    主要是 std::binary_serach,  std::upper_bound以及std::lower_bound 的用法,示例如下:

     1 std::vector<int> vtr;
     2     for (int i = 0; i < 100000; i++)
     3     {
     4         if (i%2 == 0)
     5             vtr.push_back(i);
     6     }
     7 
     8     auto find = [&](int num){
     9         return std::binary_search(vtr.begin(), vtr.end(), num); //二分查找num是否存在
    10     };
    11 
    12     std::cout << std::string(find(998) ? "Find !":"Not Find !") << std::endl;
    13     std::cout << std::string(find(999) ? "Find !" : "Not Find !") << std::endl;
    14     
    15     auto upper = [&](int num){
    16         return *std::upper_bound(vtr.begin(), vtr.end(), num); // 二分查找第一个大于num的数字
    17     };
    18     auto lower = [&](int num){
    19         return *std::lower_bound(vtr.begin(), vtr.end(), num); // 二分查找第一个大于或等于num的数字
    20     };
    21     std::cout << upper(2018) << std::endl;
    22     std::cout << lower(2018) << std::endl;
    23 
    24     sort(vtr.begin(), vtr.end(), std::greater<int>());
    25     auto upper_greate = [&](int num){
    26         return *std::upper_bound(vtr.begin(), vtr.end(), num, std::greater<int>());// 二分查找第一个小于num的数字
    27     };
    28     auto lower_greate = [&](int num){
    29         return *std::lower_bound(vtr.begin(), vtr.end(), num, std::greater<int>());// 二分查找第一个小于或等于num的数字
    30     };
    31     std::cout << upper_greate(2018) << std::endl;
    32     std::cout << lower_greate(2017) << std::endl;

    结果:

  • 相关阅读:
    细节问题
    慕课 python 操作数据库
    转 Python爬虫入门七之正则表达式
    转 python面试题
    转 Perl函数返回值用法指导
    慕课爬虫实战 爬取百度百科Python词条相关1000个页面数据
    慕课爬虫
    转 Python爬虫入门五之URLError异常处理
    转 廖雪峰 urllib
    转 Python爬虫入门四之Urllib库的高级用法
  • 原文地址:https://www.cnblogs.com/tyche116/p/9577530.html
Copyright © 2011-2022 走看看