C++之binary_search二分查找算法
功能:
查找指定元素是否存在,查到返回true 否则false。
函数原型:
bool binary_search(iterator beg, iterator end, value);
解释:beg 开始迭代器 end 结束迭代器 value 查找的元素。
注意🗣🗣:
在无序序列中不可用,且默认可用状态是升序,若要对降序数据使用binary_search算法,则要自己定义排序规则。
使用案例:
升序情况(默认状态)
调用于函数test01();
降序情况
需要自己重写排序规则,可以细分为三种方法:普通函数,函数对象,内置函数对象。调用于test02();
#include<iostream>
using namespace std;
#include <algorithm>
#include <vector>
#include<functional>
void MyPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
for_each(v.begin(), v.end(), MyPrint);
cout << endl;
bool ret = binary_search(v.begin(), v.end(), 3);
if (ret)
{
cout << "找到了" << endl;
}
else
{
cout << "未找到" << endl;
}
}
bool MySort01(const int a,const int b)
{
return a > b;
}
class MySort02
{
public:
bool operator()(const int a, const int b)
{
return a > b;
}
};
void test02()
{
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(9-i);
}
for_each(v.begin(), v.end(), MyPrint);
cout << endl;
int ret = binary_search(v.begin(), v.end(), 6, greater<int>());
if (ret)
{
cout << "找到了" << endl;
}
else
{
cout << "未找到" << endl;
}
}
int main()
{
test01();
test02();
return 0;
}
|