C++学习笔记24——泛型算法之find

1,泛型算法概述

(1)泛型是指这组算法可以操作在多种容器类型上,包括内置数组类型、甚至其他类型的序列 (比如哪些??)
(2)泛型算法本身从不执行(调用)容器操作
(3)泛型算法从不 直接添加或删除元素
(4)大多数情况下,每个算法都需要至少使用两个迭代器来标示该算法操纵的元素范围:[first, last)
(5)头文件:
#include <algorithm>
#include <numeric>


 
 

2,谓词(predicate)

The Predicate concept describes a function object that takes a single iterator argument that is dereferenced and used to return a value testable as a bool.
牵涉到function object的概念,暂时就理解成是接收单个迭代器,返回bool值的函数吧。
C语言里的sort函数已经有类似的用法,不过它是用函数指针来实现的。

3,find函数

template< class InputIt, class T >
InputIt find(InputIt first, InputIt last, const T& value );	     //(1)
	
template< class InputIt, class UnaryPredicate >
InputIt find_if( InputIt first, InputIt last, UnaryPredicate p );    //(2)
	
template< class InputIt, class UnaryPredicate >
InputIt find_if_not(InputIt first, InputIt last, UnaryPredicate q );  //(3)(since C++11)

三种find都返回 [first, last)间,满足特定条件的第一个元素的迭代器

1)  find               查找值等于 value的成员
2)  find_if         查找让谓词p返回true的成员
3)  find_if_not  查找让谓词p返回false的成员,从c++ 11开始引入
      注意:谓词p和q的函数原型应当满足如下形式:
         bool  pred ( const  Type  & a ) ;
如果输入给find()的是方向迭代器,则其返回的也是反向迭代器。
            

      4,find_first_of函数

         
t   
</pre></h1></div><div class="t-li1" style="text-indent:-5em; padding:0.2em 0px 0.2em 3em; font-family:DejaVuSans,'DejaVu Sans',arial,sans-serif; font-size:12.8px; line-height:15.36px"><span style="font-size:12.8px; line-height:15.36px">z      </span><pre name="code" class="cpp">template< class ForwardIt1, class ForwardIt2 >
ForwardIt1 find_first_of( ForwardIt1 first, ForwardIt1 last,
                          ForwardIt2 s_first, ForwardIt2 s_last );  // 1(until C++11)
template< class InputIt, class ForwardIt >
InputIt find_first_of( InputIt first, InputIt last,
                       ForwardIt s_first, ForwardIt s_last );       // 2 (since C++11)

template< class ForwardIt1, class ForwardIt2, class BinaryPredicate >
ForwardIt1 find_first_of( ForwardIt1 first, ForwardIt1 last,
                           ForwardIt2 s_first, ForwardIt2 s_last, BinaryPredicate p;	// 3 (until C++11)
                   
template< class InputIt, class ForwardIt, class BinaryPredicate >
InputIt find_first_of( InputIt first, InputIt last,
                       ForwardIt s_first, ForwardIt s_last, BinaryPredicate p );	// 4 (since C++11)

在第一段范围[first,last)内查找与第二段范围[s_first,s_last)中任意元素匹配的元素,然后返回一个迭代器,指向第一个匹配的元素。找不到则返回last迭代器。
        第一种,不使用谓词的版本,直接使用“==”操作符去匹配,第二个版本则根据谓词匹配。
       谓词p的声明应满足如下形式: bool pred(const Type1 &a, const Type2 &b);
    注意:在C++ 11之前,两组迭代器的类型必须相同,c++ 11之后两组迭代器的类型可以不同。
 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值