码迷,mamicode.com
首页 > 其他好文 > 详细

std::binary_serach, std::upper_bound以及std::lower_bound

时间:2018-09-03 12:11:09      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:ack   vector   大于   nbsp   sort   第一个   col   pre   .com   

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;

 

结果:

技术分享图片

std::binary_serach, std::upper_bound以及std::lower_bound

标签:ack   vector   大于   nbsp   sort   第一个   col   pre   .com   

原文地址:https://www.cnblogs.com/tyche116/p/9577530.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!