adjacent_find
搜索相等或满足指定条件的两个相邻元素。
template<class ForwardIterator> ForwardIterator adjacent_find( ForwardIterator _First, ForwardIterator _Last ); template<class ForwardIterator , class BinaryPredicate> ForwardIterator adjacent_find( ForwardIterator _First, ForwardIterator _Last, BinaryPredicate _Comp );
参数
_First
用于确定要搜索范围中第一个元素的位置的前向迭代器。_Last
用于确定要搜索范围中最后元素之后下一个元素的位置的前向迭代器。_Comp
给定要搜索范围内相邻元素的值需满足的条件的二元谓词。
返回值
指向相互之间相等(第一个版本中)或满足二元谓词给定条件(第二个版本中)的相邻元素对中第一个元素的前向迭代器,假设找到了此类元素对。 否则,将返回指向 _Last 的迭代器。
备注
adjacent_find 算法是不改变顺序的算法。 要搜索的范围必须是有效的;所有指针必须是可解除引用的,并且最后一个位置可从第一个位置通过递增到达。 算法的时间复杂性在范围所包含的元素数目上呈线性。
operator== 用于确定元素间的匹配必须在其操作数之间施加等效关系。
示例
// alg_adj_fnd.cpp
// compile with: /EHsc
#include <list>
#include <algorithm>
#include <iostream>
// Returns whether second element is twice the first
bool twice (int elem1, int elem2 )
{
return elem1 * 2 == elem2;
}
int main( )
{
using namespace std;
list <int> L;
list <int>::iterator Iter;
list <int>::iterator result1, result2;
L.push_back( 50 );
L.push_back( 40 );
L.push_back( 10 );
L.push_back( 20 );
L.push_back( 20 );
cout << "L = ( " ;
for ( Iter = L.begin( ) ; Iter != L.end( ) ; Iter++ )
cout << *Iter << " ";
cout << ")" << endl;
result1 = adjacent_find( L.begin( ), L.end( ) );
if ( result1 == L.end( ) )
cout << "There are not two adjacent elements that are equal."
<< endl;
else
cout << "There are two adjacent elements that are equal."
<< "\n They have a value of "
<< *( result1 ) << "." << endl;
result2 = adjacent_find( L.begin( ), L.end( ), twice );
if ( result2 == L.end( ) )
cout << "There are not two adjacent elements where the "
<< " second is twice the first." << endl;
else
cout << "There are two adjacent elements where "
<< "the second is twice the first."
<< "\n They have values of " << *(result2++);
cout << " & " << *result2 << "." << endl;
}
要求
标头:<algorithm>
命名空间: std