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

2025-10-19 19:24:24

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如何使用

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢