练习14.38
编写一个类令其检查某个给定的string对象的长度是否与一个阈值相等。使用改对象编写程序,统计并报告再输入文件中长度为1的单词有多少个、长度为2的单词有多少个、……、长度为10的单词又有多少个。
解答:
#define LAMBDA 1
#include <iostream>
#include <string>
#include <vector>
#if LAMBDA
#include <algorithm>
#endif
using namespace std;
class statistics_words{
public:
statistics_words(istream& i = cin, char c = ' '):in(i), sep(c){
for (int i = 0; i < 10; ++i){
size[i] = 0;
}
}
void operator()(istream& i = cin){
string word;
while(cin >> word){
#if LAMBDA
text.push_back(word);
#else
++size[word.size() - 1];
#endif
}
#if LAMBDA
for_each(text.cbegin(), text.cend(), [&](const string& str){++size[str.size() - 1];});
#endif
}
void show(){
cout << "\tStatistics Result\t" << endl;
for(int i = 0; i < 10; ++i){
cout << "The number of " << (i + 1) << " "<< (i ? "characters":"character")
<<" words is " << size[i] << "." << endl;
}
}
private:
istream& in;
char sep;
size_t size[10];
#if LAMBDA
vector<string> text;
#endif
};
int main(){
statistics_words test;
test();
test.show();
}
练习14.39
修改上一题的程序令其报告长度在1至9之间的单词有多少个、长度在10以上的单词又有多少个。
解答:
#define LAMBDA 1
#include <iostream>
#include <string>
#include <vector>
#if LAMBDA
#include <algorithm>
#endif
using namespace std;
class statistics_words{
public:
statistics_words(istream& i = cin, char c = ' '):in(i), sep(c){
for (int i = 0; i < 2; ++i){
size[i] = 0;
}
}
void operator()(istream& i = cin){
string word;
while(cin >> word){
#if LAMBDA
text.push_back(word);
#else
if(word.size() < 10){
++size[0];
} else {
++size[1];
}
#endif
}
#if LAMBDA
for_each(text.cbegin(), text.cend(),
[&](const string& str){
if(word.size() < 10){
++size[0];
} else {
++size[1];
}
});
#endif
}
void show(){
cout << "\n\tStatistics Result\t" << endl;
cout << "The number of [1, 9] character(s) is " << size[0] << "." << endl;
cout << "The number of [10, ∞) character is " << size[1] << "." << endl;
}
private:
istream& in;
char sep;
size_t size[2];
#if LAMBDA
vector<string> text;
#endif
};
int main(){
statistics_words test;
test();
test.show();
}
练习14.40
重新编写10.3.2节(第349页)的biggies函数,使用函数对象类替换其中的lambda表达式。
解答:
这题用到的函数对象就书中508页下方的SizeComp类。
练习14.41
你认为C++11新标准为什么要增加lambda?对于你自己来说,什么情况下会使用lambda,什么情况下会使用类?
解答:
通过lambda表达式能很方便的创建简单的函数对象。
因为两种方式都可以创建想要的函数,所以这里我可能会看心情来使用类,还是lambda表达式。
这里粘上一个连接,里面有对lambda表达式的说明和讨论(基于python的,但是用法和C++中差不多)。