二分查找是一种在有序数组中查找特定元素的高效算法。在二分查找中,upper_bound、lower_bound 和 binary_search 是三个常用的操作,C++标准库也提供了原生 API,它们都利用了二分查找,但用于解决略微不同的问题。
介绍
binary_search
定义:判断一个有序序列中是否存在指定的值。
返回值:如果序列中存在该值,返回true;否则,返回false。
用途:仅用于检查序列中是否包含某个特定的值,不提供该值的位置信息。
类似于 LeetCode704.二分查找,但是返回值是 bool 值。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
//以普通函数的方式定义查找规则
bool mycomp(int i, int j) { return i > j; }
//以函数对象的形式定义查找规则
class mycomp2 {
public:
bool operator()(const int& i, const int& j) {
return i > j;
}
};
int main() {
//从 a 数组中查找元素 4
int a[7] = { 1,2,3,4,5,6,7 };
bool haselem = binary_search(a, a + 9, 4);
cout << "haselem:" << haselem << endl;
//从 myvector 容器查找元素 3
vector<int>myvector{ 4,5,3,2,1 };
bool haselem2 = binary_search(myvector.begin(), myvector.end(), 3, mycomp2());
cout << "haselem2:" << haselem2;
return 0;
}
lower_bound
定义:在有序数组中找到第一个大于等于目标值的元素的位置。
返回值:如果数组中存在一个或多个目标值,则 lower_bound 返回指向第一个目标值的迭代器。如果所有元素都小于目标值,则返回指向数组末尾的迭代器。
用途:lower_bound 常用于查找数组中第一个大于等于目标值的元素的位置,或者获取可以插入该值而不破坏数组排序的位置。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
//以普通函数的方式定义查找规则
bool mycomp(int i, int j) { return i > j; }
//以函数对象的形式定义查找规则
class mycomp2 {
public:
bool operator()(const int& i, const int& j) {
return i < j;
}
};
int main() {
//从 a 数组中找到第一个不小于 3 的元素
int a[5] = { 1,2,3,4,5 };
int* p = lower_bound(a, a + 5, 3);
cout << "*p = " << *p << endl;
//根据 mycomp2 规则,从 myvector 容器中找到第一个违背 mycomp2 规则的元素
vector<int> myvector{ 1,2,3,4,5 };
vector<int>::iterator iter = lower_bound(myvector.begin(), myvector.end(), 3, mycomp2());
cout << "*iter = " << *iter;
return 0;
}
upper_bound
定义:在一个有序数组中找到第一个大于目标值的元素的位置。
返回值:如果数组中存在目标值,则 upper_bound 返回指向第一个大于目标值的元素的迭代器。如果所有元素都不大于目标值则返回指向数组末尾的迭代器。
用途:upper_bound 常用于确定一个范围,特别是当需要找出所有等于目标值的元素的范围时。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
//以普通函数的方式定义查找规则
bool mycomp(int i, int j) { return i > j; }
//以函数对象的形式定义查找规则
class mycomp2 {
public:
bool operator()(const int& i, const int& j) {
return i < j;
}
};
int main() {
//从 a 数组中找到第一个大于 3 的元素
int a[5] = { 1,2,3,4,5 };
int* p = upper_bound(a, a + 5, 3);
cout << "*p = " << *p << endl;
//根据 mycomp2 规则,从 myvector 容器中找到第一个违背 mycomp2 规则的元素
vector<int> myvector{ 1,2,3,4,5 };
vector<int>::iterator iter = upper_bound(myvector.begin(), myvector.end(), 3, mycomp2());
cout << "*iter = " << *iter;
return 0;
}