【每日一练】(第3期)关于STL的泛型算法count_if()

//思考题二:理解下面的代码,说说这段代码的优点和缺点。

#include  <string>
#include  <vector>
#include  <iostream>
#include  <algorithm>
using  namespace  std;

class  TestClass
{
public:
    TestClass(size_t  val  =  0)  :  bound(val)  {  }

    bool  operator()  (const  string  &s)
    {
        return  s.size()  >=  bound;
    }

    std::string::size_type    bound;
};

int  main()
{
    vector<string>  words;
    words.push_back("Hello");
    words.push_back("World");
    words.push_back("Love");
    words.push_back("C++");

    for  (int  i=3;  i<6;  ++i)
        cout  <<  count_if(  words.begin(),  words.end(),  TestClass(i)  )  <<  endl;

    system("pause");
}

【参考答案】

 这道题考察了STL的泛型算法count_if(),还考察了operator(),还考察了匿名临时对象的创建,

 核心就是这一句:

  for (int i=3; i<6; ++i)
    cout << count_if( words.begin(), words.end(), TestClass(i) ) << endl;

 TestClass(i):建立一个匿名对象(调用TestClass(size_t val = 0)构造函数),然后count_if会调用这个匿名对象的operator(),统计返回true的元素个数。

 这里使用operator()的好处是代码跟灵活,如果不用,则有多少次循环就要定义多少个函数。

 缺点是对代码阅读者的要求较高,不易理解。

 

primer中关于count_if()的描述:

执行 count_if 时,首先读取它的头两个实参所标记的范围内的元素。每读出一个元素,就将它传递给第三个实参表示的谓词函数。此谓词函数。此谓词函数需要单个元素类型的实参,并返回一个可用作条件检测的值。count_if 算法返回使谓词函数返回条件成立的元素个数。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值