upper_bound
时间: 2023-06-21 17:17:42 浏览: 42
upper_bound函数是C++ STL中的一个函数,用于查找有序序列中第一个大于给定值的元素的位置。该函数的定义如下:
```c++
template <class ForwardIterator, class T>
ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last, const T& val);
```
其中,first和last是指向有序序列中要进行查找的范围的迭代器,val是要查找的值。该函数返回一个迭代器,指向序列中第一个大于val的元素位置。如果序列中不存在大于val的元素,则返回last。
以下是一个使用upper_bound函数的例子:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[] = {1, 2, 3, 3, 4, 4, 5, 6};
int n = sizeof(a) / sizeof(int);
int x = 4;
int *p = upper_bound(a, a + n, x);
cout << "upper_bound of " << x << " : " << (p - a) << endl;
return 0;
}
```
输出结果为:upper_bound of 4 : 6
在本例中,数组a中有序存储了一组整数,我们要查找第一个大于4的元素的位置。通过调用upper_bound函数,返回一个迭代器指向数字4后面的位置,即数字5的位置。由于数组下标从0开始,因此输出结果为6。