第十四章 14.8.1节练习

练习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++中差不多)。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值