binary_search
功能描述:
- 查找指定元素是否存在。且二分查找法的查找速度非常快
函数原型:
-
bool binary_search(iterator beg, iterator end, value);
// 查找指定的元素,查到 返回true 否则false
// 注意: 在无序序列中有可能找得到,有可能找不到。
// beg 开始迭代器
// end 结束迭代器
// value 查找的元素
它的底层源码如下:
#include<iostream>
using namespace std;
#include<algorithm>
#include<functional>
#include<vector>
#include<string>
void Myprint1(int n) {
cout << n << " ";
}
void test01() {
cout << "针对内置数据类型" << endl;
vector<int> v1;
for (int i = 0; i < 10; i++) {
v1.push_back(i);
}
cout << "容器v1里的元素如下:" << endl;
for_each(v1.begin(), v1.end(), Myprint1);
cout << endl << endl;
bool a1=binary_search(v1.begin(), v1.end(), 20);
if (a1 == 0) {
cout << "容器v1里没有20这个元素!!" << endl << endl;
}
else {
cout << "用二分查找查找到20!" << endl;
}
bool a2 = binary_search(v1.begin(), v1.end(), 6);
if (a2 == 0) {
cout << "容器v1里没有6这个元素!!" << endl << endl;
}
else {
cout << "用二分查找查找到6!" << endl<<endl<<endl;
}
}
int main() {
test01();
return 0;
}