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.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的专栏
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值