find_first_of函数和其他函数类似,提供了两个函数,一个支持仿函数,一个内置关系运算符(以默认的<操作符).该系列函数都是以第一个范围的元素为准.
函数功能:返回第一个既在_First1-_Last1中,又在_First2-_Last2中元素的位置(第一个范围).
//TEMPLATE FUNCTION find_first_of
template<class_FwdIt1,
class_FwdIt2> inline
_FwdIt1 _Find_first_of(_FwdIt1 _First1,_FwdIt1 _Last1,
_FwdIt2 _First2, _FwdIt2_Last2)
{ // look for one of [_First2, _Last2) that matches element
for (;_First1 != _Last1; ++_First1)
for(_FwdIt2 _Mid2 = _First2; _Mid2 != _Last2; ++_Mid2)//纯粹的两次循环对比
if (*_First1 == *_Mid2)
return (_First1);
return(_First1);
}
template<class_FwdIt1,
class_FwdIt2> inline
_FwdIt1 find_first_of(_FwdIt1 _First1,_FwdIt1 _Last1,
_FwdIt2 _First2, _FwdIt2_Last2)
{ // look for one of [_First2, _Last2) that matches element
_DEBUG_RANGE(_First1, _Last1);
_DEBUG_RANGE(_First2, _Last2);
return(_Rechecked(_First1,
_Find_first_of(_Unchecked(_First1),_Unchecked(_Last1),
_Unchecked(_First2),_Unchecked(_Last2))));
}
函数功能: 返回第一个既在_First1-_Last1中,又在_First2-_Last2中使得_Pred为真的位置(同样是第一个区间).
//TEMPLATE FUNCTION find_first_of WITH PRED
template<class_FwdIt1,
class_FwdIt2,
class_Pr> inline
_FwdIt1 _Find_first_of(_FwdIt1 _First1,_FwdIt1 _Last1,
_FwdIt2 _First2, _FwdIt2_Last2, _Pr _Pred)
{ // look for one of [_First2, _Last2) satisfying _Pred withelement
for (;_First1 != _Last1; ++_First1)
for(_FwdIt2 _Mid2 = _First2; _Mid2 != _Last2; ++_Mid2)
if (_Pred(*_First1, *_Mid2))
return (_First1);
return(_First1);
}
template<class_FwdIt1,
class_FwdIt2,
class_Pr> inline
_FwdIt1 find_first_of(_FwdIt1 _First1,_FwdIt1 _Last1,
_FwdIt2 _First2, _FwdIt2_Last2, _Pr _Pred)
{ // look for one of [_First2, _Last2) satisfying _Pred with element
_DEBUG_RANGE(_First1, _Last1);
_DEBUG_RANGE(_First2, _Last2);
_DEBUG_POINTER(_Pred);
return(_Rechecked(_First1,
_Find_first_of(_Unchecked(_First1),_Unchecked(_Last1),
_Unchecked(_First2),_Unchecked(_Last2), _Pred)));
}
这两个函数中规中矩.没有特别需要留意的地方.
举例:
template<typenameT>
bool equal_three( T _value1,T _value2 )
{
return_value1 == ++ _value2;
}
int main()
{
vector<int>vecInt;
vecInt.push_back( 5 );
vecInt.push_back( 3 );
vecInt.push_back( 7 );
vecInt.push_back( 4 );
vecInt.push_back( 9 );
vecInt.push_back( 3 );
vecInt.push_back( 5 );
vecInt.push_back( 1 );
vecInt.push_back( 3 );
list<int>lstInt;
lstInt.push_back( 2 );
lstInt.push_back( 4 );
lstInt.push_back( 3 );
vector<int>::iteratoriterFind = find_first_of( vecInt.begin(),vecInt.end(),lstInt.begin(),lstInt.end());
if (iterFind != vecInt.end() )
{
cout<<*iterFind<<"\n";
}
iterFind = find_first_of(vecInt.begin(),vecInt.end(),lstInt.begin(),lstInt.end(),equal_three<int> );
if (iterFind != vecInt.end() )
{
cout<<*iterFind<<"\n";
}
system( "pause");
return0;
}