当前位置:编程学习 > C/C++ >>

find/find_if详解

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.zzzyk.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的专栏
补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,