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

来源:互联网 发布:资管新规 解读 知乎 编辑:程序博客网 时间:2024/05/23 20:23
//思考题二:理解下面的代码,说说这段代码的优点和缺点。#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 算法返回使谓词函数返回条件成立的元素个数。