lower_bound和upper_bound函数实际演示
时间: 2023-05-27 21:07:02 浏览: 72
假设有一个已经排好序的vector:
```cpp
vector<int> nums = {1, 3, 3, 5, 7, 9};
```
我们可以使用lower_bound和upper_bound函数来查找某个元素在该vector中的位置。
lower_bound函数:
```cpp
auto it = lower_bound(nums.begin(), nums.end(), 3);
cout << it - nums.begin() << endl; // 1
```
这里的lower_bound函数返回一个迭代器,指向第一个大于等于3的元素。因此,它返回的迭代器指向的是3,它在vector中的下标为1。
如果要查找的元素在vector中不存在,lower_bound函数也能返回该元素应该插入的位置:
```cpp
auto it2 = lower_bound(nums.begin(), nums.end(), 4);
cout << it2 - nums.begin() << endl; // 3
```
这里的lower_bound函数返回一个迭代器,指向第一个大于等于4的元素。由于vector中没有4,所以它返回的迭代器指向的是5,它在vector中的下标为3。
upper_bound函数:
```cpp
auto it3 = upper_bound(nums.begin(), nums.end(), 3);
cout << it3 - nums.begin() << endl; // 3
```
这里的upper_bound函数返回一个迭代器,指向第一个大于3的元素。因此,它返回的迭代器指向的是5,它在vector中的下标为3。
如果要查找的元素在vector中不存在,upper_bound函数也能返回该元素应该插入的位置:
```cpp
auto it4 = upper_bound(nums.begin(), nums.end(), 4);
cout << it4 - nums.begin() << endl; // 3
```
这里的upper_bound函数返回一个迭代器,指向第一个大于4的元素。由于vector中没有4,所以它返回的迭代器指向的是5,它在vector中的下标为3。
综上所述,lower_bound和upper_bound函数可以帮助我们快速查找某个元素在已排序的容器中的位置。