C++ lower_bound()、upper_bound()

Posted on   foghorn  阅读(59)  评论(0编辑  收藏  举报

lower_bound(arr, x)函数用于查找arr中第一个大于或等于x的元素,如果arr是容器,则返回的是迭代器,如果arr是普通数组,则返回的是指针。
upper_bound(arr, x)查找arr中第一个大于x的元素,如果x有多个,则查找最后一个。
两个函数必须在有序序列上操作,在头文件#include 中。

// lower_bound/upper_bound example
#include <iostream>     // std::cout
#include <algorithm>    // std::lower_bound, std::upper_bound, std::sort
#include <vector>       // std::vector

int main () {
  int myints[] = {10,20,30,30,20,10,10,20};
  std::vector<int> v(myints,myints+8);           // 10 20 30 30 20 10 10 20

  std::sort (v.begin(), v.end());                // 10 10 10 20 20 20 30 30

  std::vector<int>::iterator low,up;
  low=std::lower_bound (v.begin(), v.end(), 20); //          ^
  up= std::upper_bound (v.begin(), v.end(), 20); //                   ^

  std::cout << "lower_bound at position " << (low- v.begin()) << '\n';
  std::cout << "upper_bound at position " << (up - v.begin()) << '\n';

  return 0;
}

输出:
lower_bound at position 3
upper_bound at position 6
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)

随笔 - 73, 文章 - 0, 评论 - 4, 阅读 - 45689

Copyright © 2025 foghorn
Powered by .NET 9.0 on Kubernetes

点击右上角即可分享
微信分享提示