c++语言中的std::upper_bound如何使用

 时间:2026-02-15 15:26:12

1、该函数基本语法格式为:

upper_bound (ForwardIterator first, ForwardIterator last,  const T& val)

返回的是在范围[ first, last)内第一个大于val的元素所在的位置,类型与first,last一致。

c++语言中的std::upper_bound如何使用

2、第一种用法

对于STL库中的容器vector,可以结合内嵌的迭代器iterator来使用upper_bound 函数。

#include<bits/stdc++.h>

#include<vector>

using namespace std;

int main()

{

      vector<int> v={0 ,2 ,1 ,4 ,7 ,6};

      vector<int>::iterator up1;

      up1=upper_bound(v.begin(),v.end(),3);

      cout<<up1-v.begin()<<endl;

}

c++语言中的std::upper_bound如何使用

3、最后输出的结果是vector 中第一个大于3的元素所在的位置。

输出为3,没有问题。

c++语言中的std::upper_bound如何使用

4、第二种用法:

对于数组又改如何操作呢?

类似的,我们可以写下如下程序:

#include<bits/stdc++.h>

using namespace std;

int main()

{

      int a[6]={1,3,5,6,7,9};

      int temp=upper_bound(a,a+6,7)-a;

      cout<<temp<<endl;

}

c++语言中的std::upper_bound如何使用

5、最后输出的结果是5,

符合条件。

c++语言中的std::upper_bound如何使用

6、类似的我们还可以在数组中设定的区间进行查找,就不给出代码了

用法:int t=upper_bound(a+l,a+r,m)-a

在这里,a表示数组第一个元素所在的指正,l与R可以确定数组内的区间

c++语言中的std::upper_bound如何使用

  • 如何用C++求字符串的长度?
  • python中str()的用法
  • 转义字符有哪些
  • python中input怎么输入数字
  • 直线与平面的交点怎么求
  • 热门搜索
    清白的意思 新陈代谢的意思 爬爬垫什么牌子好 安居乐业是什么意思 玩游戏用什么cpu好 立秋是什么意思 不耻下问是什么意思 光彩夺目的意思是什么 一元复始 万象更新是什么意思 可圈可点是什么意思