STL中二分查找函数
程序员文章站
2022-03-14 09:57:51
...
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int a[12] = {1,6,31,66,67,68,69,70,71,73,76,79};
int c[12] = {79,76,73,71,70,69,68,67,66,31,6,1};
vector<int> b;
b.push_back(1);
b.push_back(6);
b.push_back(31);
b.push_back(66);
b.push_back(67);
b.push_back(68);
b.push_back(69);
b.push_back(70);
b.push_back(71);
b.push_back(73);
b.push_back(76);
b.push_back(79);
int n;
binary_search(b.begin(),b.end(),n)//返回得是bool值,也适用于数组,用于判断有没有找到
if(binary_search(a,a+12,n))printf("find %d\n",n);
else printf("%d is not in array\n");
if(binary_search(b.begin(),b.end(),n))printf("find %d\n",n);
else printf("%d is not in array\n",n);*/
>>>
66
find 66
find 66
99
6422256 is not in array
99 is not in array
lower_bound(b.begin(),b.end(),n);//返回得是迭代器,也适用于数组(用对应类型得指针接着就好),用于查找第一个不小于n得值得位置(p-1就是第一个比n小的索引了)
int *p;
vector<int>::iterator it;
p = lower_bound(a,a+12,n);
if(p != a + 12)
{
printf("The first num which is bigger(or equal) than %d is %d,index is : %d\n",n,*p,(p - a));
}
else printf("Not found!\n");
it = lower_bound(b.begin(),b.end(),n);
if(it != b.end())
{
printf("The first num which is bigger(or equal) than %d is %d,index is : %d\n",n,*it,distance(b.begin(),it));
}
else printf("Not found!\n");
>>>
6
The first num which is bigger(or equal) than 6 is 6,index is : 1
The first num which is bigger(or equal) than 6 is 6,index is : 1
1
The first num which is bigger(or equal) than 1 is 1,index is : 0
The first num which is bigger(or equal) than 1 is 1,index is : 0
0
The first num which is bigger(or equal) than 0 is 1,index is : 0
The first num which is bigger(or equal) than 0 is 1,index is : 0
99
Not found!
Not found!
upper_bound(b.begin(),b.end(),n);//返回得是迭代器,也适用于数组(用对应类型得指针接着就好),用于查找第大于n得值得位置
int *p;
vector<int>::iterator it;
p = upper_bound(a,a+12,n);
if(p != a+12)
{
printf("The first num which is bigger than %d is %d,index is : %d\n",n,*p,(p - a));
}
else printf("Not found!\n");
it = upper_bound(b.begin(),b.end(),n);
if(it != b.end())
{
printf("The first num which is bigger than %d is %d,index is : %d\n",n,*it,distance(b.begin(),it));
}
else printf("Not found!\n");*/
>>>
6
The first num which is bigger than 6 is 31,index is : 2
The first num which is bigger than 6 is 31,index is : 2
78
The first num which is bigger than 78 is 79,index is : 11
The first num which is bigger than 78 is 79,index is : 11
79
Not found!
Not found!
对于lower_bound & upper_bound()还有一个第四个参数greater<type>(),他会把不小于变为不大于得查找,把大于变为小于得查找,但是相反,他要求得顺序不是递增,而是递减!!!
int *p = lower_bound(c,c+12,n,greater<int>());//传入第四个参数,查找第一个小于等于n得值
if(p != c+12)
{
printf("The first num which is smaller(or equal) than %d is %d,index is : %d\n",n,*p,(p - c));
}
else printf("Not found!\n");
>>>
6
The first num which is smaller(or equal) than 6 is 6,index is : 10
5
The first num which is smaller(or equal) than 5 is 1,index is : 11
0
Not found!
忘了提一下distence函数他是用于迭代器得用于计算他们之间的距离~~~(注意好传值的先后顺序)
上一篇: C++ STL中的 二分查找
下一篇: 查找-二分查找