神秘博客

C++ Primer Plus [第六版]第18章复习题答案

7

书上的答案应该是有误的,我用VS2017无法直接引用lambda表达式,得添加function包装器才行

#include <iostream>
#include <array>
#include <functional>

const int Size = 5;
template <typename T>
void sum(std::array<double, Size> a, T &fp);

int main()
{
  using namespace std;

  double total = 0.0;
  array<double, Size> temp_c = { 32.1,34.3,37.8,35.2,34.7 };
  function<void(double)> f = [&total](double x) {total += x; };
  sum(temp_c, f);
  cout << "total = " << total << endl;

  system("pause");
  return 0;
}

template <typename T>
void sum(std::array<double, Size> a, T &fp)
{
  for (auto pt = a.begin(); pt != a.end(); pt++)
    fp(*pt);
}

 

版权说明:
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注

觉得文章有用就请我吃包辣条吧

微信扫一扫打赏