【问题标题】:Why is the output different even though the expressions are the same in lambda expression?为什么即使 lambda 表达式中的表达式相同,输出也会不同?
【发布时间】:2021-12-12 14:22:32
【问题描述】:

我对这样的 lambda 表达式有疑问:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std; 

int sum(vector<int>& v){
    int total = 0;
    auto lambda = for_each(v.begin(), v.end(), [&total](int n){total += n;});
    lambda; // lambda expression doesn't work.
    for_each(v.begin(), v.end(), [&total](int n){total += n;}); // work same as I intended.
    return total;
}

int main(void){
    vector<int> v = {1, 2, 3, 4, 5};
    cout << sum(v) << endl; // 30 (I think this should be 45.)
}

我认为lambda; 可以做与for_each 算法相同的事情。为什么lambda; 不起作用?

【问题讨论】:

标签: c++ lambda


【解决方案1】:

根据cppreferencefor_each(...) 调用返回传递给函数的UnaryFunction

在这种情况下,for_each 返回 UnaryFunction

[&total](int n){total += n;}

lambda(5) 会将 total 的值增加 5。

解决方案是将for_each 调用放在一个单独的函数中——这实际上是一个“求和”函数。 这已经由std:accumulate 函数完成

std::accumulate(v.begin(), v.end(), 0);

【讨论】:

    【解决方案2】:

    如果不考虑累加变量total这个声明的副作用

    auto lambda = for_each(v.begin(), v.end(), [&total](int n){total += n;});
    

    其实等价于

    auto lambda = [&total](int n){total += n;};
    

    所以这个说法

    lambda; // lambda expression doesn't work.
    

    没有意义。

    所以 lambda 表达式的声明只是多余的。

    实际上你在这个声明中调用了算法 std::for_each 两次

    auto lambda = for_each(v.begin(), v.end(), [&total](int n){total += n;});
    

    在此声明中

    for_each(v.begin(), v.end(), [&total](int n){total += n;});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多