当前位置:C++技术网 > 资讯 > STL中binary_search算法实现数据元素的二分查找

STL中binary_search算法实现数据元素的二分查找

更新时间:2016-03-23 22:09:06浏览次数:1+次

假设要在数组中查找一项。最简单的方法就是顺序查找,不过,顺序查找最大的缺点就是一旦遇到了大数据的查找,效率就坑死你。因此,我们通常会用二分查找算法来实现。我想你对于二分查找,应该不陌生,最起码听过。在C++标准程序库中,stl为我们封装了这个算法的过程,最终命名为binary_search。下面,我们看看这个算法函数的介绍:
bool binary_search(ForwardItarator beg, ForwardItarator end, const T& value);
bool binary_search(ForwardItarator beg, ForwardItarator end, const T& value,BinaryPredicate op);

对于二分查找有两种方式来调用,不过第二种不常用。当我们要获得被搜寻元素的位置时,应该使用lower_bound(),upper_bound(),equal_range()。为什么二分查找效率更高?主要就是因为,他是对数复杂度。最后的执行次数是Log型的。而有一点你不知道的是,当我们调用这个算法函数时,如果搭配的不是随机存取迭代器,那就就是线性复杂度,反之就是对数复杂度。什么是随机存取迭代器?STL中的vecotr::itator就是随机迭代器,它可以用[]来取vector中任意一个元素。list::itator就不是随即迭代器,因为它不能用[]来取list中的元素。而deque等容器配接的迭代器也是随机存取迭代器。下面,我们来实际操作一个二分查找:

#include "iostream"
#include "string"
#include "algorithm"
#include "vector"
#include "string"
#include "iterator"

using namespace std;

int main()
{
	/*vector<int> IntVec;
	istream_iterator<int> in(cin);
	istream_iterator<int> eof;
	copy(in,eof,back_inserter(IntVec));

	if (binary_search(IntVec.begin(),IntVec.end(),6))
	{
		cout<<"找到了!"<<endl;
	}
	else
	{
		cout<<"没有找到!"<<endl;
	}*/

	vector<string> Intstr;
	copy(istream_iterator<string>(cin),istream_iterator<string>(),back_inserter(Intstr));
	if (binary_search(Intstr.begin(),Intstr.end(),"hello"))
	{
		cout<<"找到了!"<<endl;
	}
	else
	{
		cout<<"没有找到!"<<endl;
	}

	system("pause");
	return 0;
}