binary_search
测试是否在与指定的值相等或与其实际上是等效的二进制谓词指定的排序的范围的元素。
template<class ForwardIterator, class Type>
bool binary_search(
ForwardIterator _First,
ForwardIterator _Last,
const Type& _Val
);
template<class ForwardIterator, class Type, class BinaryPredicate>
bool binary_search(
ForwardIterator _First,
ForwardIterator _Last,
const Type& _Val,
BinaryPredicate _Comp
);
参数
_First
解决仅向前迭代器的第一个元素的位置在要搜索的范围。_Last
解决仅向前的迭代器通过最终元素的位置一在要搜索的范围。_Val
要求的值由元素或)的值匹配必须为二进制谓词指定的元素值满足条件。_Comp
定义含义的用户定义的谓词函数对象哪个元素比另一个小于。 二进制谓词采用两个参数并返回 true,在满足和 false,在未满足。
返回值
true,如果元素在具有指定值相等或等效的范围中找到;否则,false。
备注
引用的排序的源范围必须是有效的;所有指针必须dereferenceable,因此,在序列中,最后位置必须是可访问的从开始按增量。
必须每个使该排序的大小,而对 binary_search 算法的应用程序的前提条件与排序的相同与与将算法使用排序合并的大小。
binary_search不修改源范围。
向前迭代的值类型需要小于可将排序,因此,命名两个组件,可以确定为它们是等效的(来讲都比其他不小于)或一个比其他小于。 这将导致排序在非等价的组件间
算法的复杂否则是对数为随机访问迭代器和线性,与步骤数比例为(_Last –_First)。
示例
// alg_bin_srch.cpp
// compile with: /EHsc
#include <list>
#include <vector>
#include <algorithm>
#include <iostream>
// Return whether modulus of elem1 is less than modulus of elem2
bool mod_lesser ( int elem1, int elem2 )
{
if (elem1 < 0)
elem1 = - elem1;
if (elem2 < 0)
elem2 = - elem2;
return elem1 < elem2;
}
int main( )
{
using namespace std;
list <int> L;
list <int>::iterator Iter;
bool b1, b2;
L.push_back( 50 );
L.push_back( 10 );
L.push_back( 30 );
L.push_back( 20 );
L.push_back( 25 );
L.push_back( 5 );
L.sort( );
cout << "L = ( " ;
for ( Iter = L.begin( ) ; Iter != L.end( ) ; Iter++ )
cout << *Iter << " ";
cout << ")" << endl;
b1 = binary_search( L.begin( ), L.end( ), 10 );
if ( b1 )
cout << "There is an element in list L with a value equal to 10."
<< endl;
else
cout << "There is no element in list L with a value equal to 10."
<< endl;
// a binary_search under the binary predicate greater
L.sort ( greater<int> ( ) );
b2 = binary_search( L.begin( ), L.end( ), 10 , greater<int> ( ) );
if ( b2 )
cout << "There is an element in list L with a value equivalent to 10 "
<< "under greater than." << endl;
else
cout << "No element in list L with a value equivalent to 10 "
<< "under greater than." << endl;
// a binary_search under the user-defined binary predicate mod_lesser
vector <int> v1;
vector <int>::iterator Iter1;
int i;
for ( i = -2 ; i <= 4 ; i++ )
{
v1.push_back( i );
}
sort ( v1.begin ( ) , v1.end ( ) , mod_lesser );
cout << "Ordered under mod_lesser, vector v1 = ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")" << endl;
bool b3 = binary_search( v1.begin( ), v1.end( ), -3 , mod_lesser );
if ( b3 )
cout << "There is an element with a value equivalent to -3 "
<< "under mod_lesser." << endl;
else
cout << "There is not an element with a value equivalent to -3 "
<< "under mod_lesser." << endl;
}
要求
标头: <algorithm>
命名空间: std