C++中的upper_bound 和lower_bound比较容易弄混。记住的方法是根据名字记住其功能,如upper_bound表示以某个数为上限,这个数应该放在哪个位置;lower_bound表示以某个数为下限,这个数应该放在哪个位置。同时注意数组应该提前拍好序。
举个例子:
#include<bits/stdc++.h>
using namespace std;
int main() {
int a[] = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4};
cout << (lower_bound(a, a + 12, 4) - a) << endl; //输出 9
cout << (upper_bound(a, a + 12, 4) - a) << endl; //输出 12
cout << (lower_bound(a, a + 12, 1) - a) << endl; //输出 0
cout << (upper_bound(a, a + 12, 1) - a) << endl; //输出 3
cout << (lower_bound(a, a + 12, 3) - a) << endl; //输出 6
cout << (upper_bound(a, a + 12, 3) - a) << endl; //输出 9
cout << (lower_bound(a, a + 12, 5) - a) << endl; //输出 12
cout << (upper_bound(a, a + 12, 5) - a) << endl; //输出 12
cout << (lower_bound(a, a + 12, 0) - a) << endl; //输出 0
cout << (upper_bound(a, a + 12, 0) - a) << endl;

本文介绍了C++中用于排序数组的upper_bound和lower_bound函数,通过名字含义帮助理解其功能:upper_bound找到大于等于目标值的插入位置,而lower_bound找到小于等于目标值的插入位置。举例说明了两者在查找过程中的应用。
最低0.47元/天 解锁文章
1115

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



