find/find_if:
函數功能:返回元素值為_Val的迭代器
template<class _InIt,
class_Ty> inline
_InIt find(_InIt _First, _InIt _Last, const _Ty& _Val)
{ // find first matching _Val
_DEBUG_RANGE(_First, _Last);
return(_Rechecked(_First,
_Find(_Unchecked(_First),_Unchecked(_Last), _Val)));
}
// TEMPLATEFUNCTION find
template<class _InIt,
class_Ty> inline
_InIt _Find(_InIt _First,_InIt _Last, const _Ty& _Val)
{ // find first matching _Val
for(; _First != _Last; ++_First)
if (*_First == _Val)
break;
return(_First);
}
注意:
◆ 函數返回值的區間在[begin,end]之間.因此當我們調用這個函數的時候,我們應將返回的值與end比較.
◆ 順序容器不要使用算法庫的find操作,而應該使用其本身提供的find.(原因很簡單,自己肯定最了解自己)
◆ 同樣最好不要改變區間的值 www.2cto.com
find_if函數實現:
//TEMPLATE FUNCTION find_if
template<class _InIt,
class_Pr> inline
_InIt _Find_if(_InIt _First, _InIt_Last, _Pr _Pred)
{ // find first satisfying _Pred
for (;_First != _Last; ++_First)
if(_Pred(*_First))//這裡使用單個參數的bool型函數:bool(*pFun)( T )
break;
return(_First);
}
template<class _InIt,
class_Pr> inline
_InIt find_if(_InIt _First, _InIt_Last, _Pr _Pred)
{ // find first satisfying _Pred
_DEBUG_RANGE(_First, _Last);
_DEBUG_POINTER(_Pred);
return(_Rechecked(_First,
_Find_if(_Unchecked(_First),_Unchecked(_Last), _Pred)));
}
函數功能:返回使得_Pred為true的迭代器.
舉例:
template<typenameT>
bool equal_ten( T _value )
{
return_value == 3;
}
int main()
{
vector<int>vecInt;
vecInt.push_back( 2 );
vecInt.push_back( 5 );
vecInt.push_back( 7 );
vecInt.push_back( 3 );
vecInt.push_back( 2 );
vecInt.push_back( 4 );
vecInt.push_back( 3 );
vecInt.push_back( -17 );
vecInt.push_back( 3 );
vector<int>::iteratoriterFind = find( vecInt.begin(),vecInt.end(),4 );
if (iterFind != vecInt.end() )//注意判斷是否已經找到
{
cout<<*iterFind<<"\n";
}
iterFind = find_if(vecInt.begin(),vecInt.end(),equal_ ten <int>);
if (iterFind != vecInt.end() )
{
cout<<*iterFind<<"\n";
}
system( "pause");
return0;
}
摘自 yuanweihuayan的專欄