关于STL中的二分查找
(1)STL中关于二分查找的函数有三个:lower_bound 、upper_bound 、binary_search
—— 这三个函数都运用于有序区间(当然这也是运用二分查找的前提)
(2)ForwardIter lower_bound(ForwardIter first, ForwardIter last,const _Tp& val)
算法返回一个非递减序列[first, last)中的第一个大于等于值val的位置;
(3)ForwardIter upper_bound(ForwardIter first, ForwardIter last, const _Tp& val)
算法返回一个非递减序列[first, last)中的第一个大于值val的位置。
(4)binary_search(ForwardIter first, ForwardIter last, const _Tp& val) 返回是否存在val
大家都知道,二分查找是在排序后的基础上来对其进行查找操作。
所以在使用binary_search的时候,需要对将要查找的容器进行排序。
特别强调:排序的必须是要从小到大
下面就通过简单易懂的代码对其讲解
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
vector <int> V;
int a[10];
set <int> S;
struct Node//结构体定义以及运算符重载
{
int x,y;
bool operator<(const Node &rhs)const
{
if(x == rhs.x)
return y < rhs.y;
else
return x < rhs.x;
}
}nodes[10];
int main()
{
///数组
for(int i = 0; i < 10; ++ i)
a[i] = i * 2;
int p, q;
sort(a, a + 10);
p = lower_bound(a, a + 10, 4) - a;
q = upper_bound(a, a + 10, 4) - a;
cout << p << endl << q << endl;
if(binary_search(a, a + 10, 12))
cout << "array : Yes" << endl;
else
cout << "array :No" << endl;
///vector
V.push_back(2);
V.push_back(3);
V.push_back(1);
sort(V.begin(), V.end());//对vector 的排序
if(binary_search(V.begin(), V.end(), 5)) // 对vector进行二分查找
cout << "vector : Yes" << endl;
else
cout << "vector : No" << endl;
/// set
for(int i = 0; i < 10; ++ i)
S.insert(i);
set <int> :: iterator itb = S.begin();
set <int> :: iterator ite = S.end();
if(binary_search(itb, ite, 1)) // 对vector进行二分查找
cout << "set : Yes" << endl;
else
cout << "set : No" << endl;
/*
在对结构体进行二分操作之前,肯定需要先对其排序。
对结构体排序就需要用到运算符重载,对结构体中的<进行重载,
排序可以直接用sort排序,或者是定义一个结构体类型的set,set会对其去重排序。
然后就可以使用二分查找了。
*/
for(int i = 0; i < 10; ++ i)
nodes[i].x = i, nodes[i].y = i;
sort(nodes, nodes + 10);
Node tmp;
tmp.x = 5, tmp.y = 5;
if(binary_search(nodes, nodes + 10, tmp))
cout << "struct : Yes" << endl;
else
cout << "struct : No" << endl;
p = lower_bound(nodes, nodes + 10, tmp) - nodes;
q = upper_bound(nodes, nodes + 10, tmp) - nodes;
cout << p << endl << q << endl;
return 0;
}