【每日一练】(第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 算法返回使谓词函数返回条件成立的元素个数。
- 【每日一练】(第3期)关于STL的泛型算法count_if()
- 【每日一练】(第2期)关于静态成员的理解
- 【每日一练】(第1期)关于调用规范和函数指针
- 【每日一练】(第4期)C++编程规范-继承
- 【每日一练】】(第7期)C++编程规范之类的设计2
- 算法每日一练
- C++每日一练(STL算法——sort)
- C++每日一练(STL算法——find)
- C++每日一练(STL算法——copy)
- C++每日一练(STL算法——remove)
- 算法每日一练1
- java算法每日一练
- 每日一练3
- 每日一练------判断是一年的第几天
- STL algorithm算法count_if(11)
- STL算法之count. count_if
- C++每日一练(STL算法——for each)
- IOS 每日一练 第一天
- 视频编码的守望者--Jason Garrett-Glaser
- poi excel带公式导出
- 45个android实例源码
- 大型企业Exchange 2010部署方案 – 分割全局地址列表
- 1503 Integer Inquiry
- 【每日一练】(第3期)关于STL的泛型算法count_if()
- 城主争霸赛 改进版 我要开挂!永恒降临! .
- 服务器性能测试典型工具介绍
- mysql 怎样清空一个数据库中的所有表
- Android应用程序键盘(Keyboard)消息处理机制分析
- S3C2440对nandflash的操作
- Linux输入子系统:输入设备编程指南 -- input-programming.txt
- android 动态切换主题,动态换肤
- MySql与Java的时间类型