STL中二分查找函数
程序员文章站
2022-03-14 09:57:15
...
1. binary_search(b.begin(),b.end(),n)//返回得是bool值,也适用于数组,用于判断有没有找到。
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int a[10];
for (int i = 0; i < 10; i++)
a[i] = i + 1;
if (binary_search(a, a + 10, 5) == true)
printf("Yes\n");
else
printf("No\n");
if (binary_search(a, a + 10, 20) == true)
printf("Yes\n");
else
printf("No\n");
return 0;
}
>>Yes
>>No
2. lower_bound(b.begin(),b.end(),n);//返回得是迭代器,也适用于数组(用对应类型得指针接着就好),用于查找第一个大于等于n得值得位置(p-1就是第一个比n小的索引了)
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int a[10];
for (int i = 0; i < 10; i++)
a[i] = i * 2;
//a[]={0,2,4,6,8,10,12,14,16,18};
int pos = lower_bound(a, a + 10, 4) - a;
printf("%d\n", pos);
pos = lower_bound(a, a + 10, 5) - a;
printf("%d\n", pos);
return 0;
}
>>2
>>3
3. upper_bound(b.begin(),b.end(),n);//返回得是迭代器,也适用于数组(用对应类型得指针接着就好),用于查找第大于n得值得位置
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int a[10];
for (int i = 0; i < 10; i++)
a[i] = i * 2;
//a[]={0,2,4,6,8,10,12,14,16,18};
int pos = upper_bound(a, a + 10, 4) - a;
printf("%d\n", pos);
pos = upper_bound(a, a + 10, 5) - a;
printf("%d\n", pos);
return 0;
}
>>3
>>3
4. 对于lower_bound & upper_bound()还有一个第四个参数greater<type>(),他会把不小于变为不大于得查找,把大于变为小于得查找,但是相反,他要求得顺序不是递增,而是递减!!!此外,还必须加头文件#include <functional>
#include <iostream>
#include <cstdio>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
bool cmp(int x, int y)
{
return x > y;
}
int main()
{
int a[10];
for (int i = 0; i < 10; i++)
a[i] = i * 2;
//a[]={0,2,4,6,8,10,12,14,16,18};
//注意:这种用法需要数组从从大到小排序
sort(a, a + 10, cmp);
int pos = lower_bound(a, a + 10, 4, greater<int>()) - a;
printf("%d\n", pos);
pos = lower_bound(a, a + 10, 5, greater<int>()) - a;
printf("%d\n", pos);
pos = upper_bound(a, a + 10, 4, greater<int>()) - a;
printf("%d\n", pos);
pos = upper_bound(a, a + 10, 5, greater<int>()) - a;
printf("%d\n", pos);
return 0;
}
>>7
>>7
>>8
>>7
上一篇: 方法static和new的区别
下一篇: 二分查找与STL中的上下界查找函数