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;

结果:

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