lower_bound()返回一个迭代器,而insert会在此迭代器之前插入元素
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int arr[3] = {3, 4, 5};
vector<int> v(arr, arr + 3);
int x = 4;
/////
vector<int>::iterator ite = lower_bound(v.begin(), v.end(), x); // 找到第一个大于等于数字x的数字
// 如果找到返回该数字的地址 如果没找到返回end
cout << *ite << endl;
// 通过返回的地址 - 起始地址begin 得到找到数字在数组中的下标(从0开始)
cout << ite - v.begin() << endl;
// upper_bound() 与 lower_bound 唯一区别就是找到第一个大于数字x的数字
// 在从小到大的数组中,重载lower_bound 与 upper_bound
ite = lower_bound(v.begin(), v.end(), x, greater<int>()); // 找到第一个小于等于数字x的数字
return 0;
}
C++标准库:lower_bound与upper_bound的使用解析
本文介绍了C++中`lower_bound`和`upper_bound`函数的用法,这两个函数用于在排序容器中查找指定元素的位置。示例代码展示了如何在向量中查找并插入元素,同时对比了两者之间的区别。通过对这两个函数的理解,可以更高效地操作有序数据集合。

被折叠的 条评论
为什么被折叠?



