如何从C ++ 11匿名函数内部访问局部变量? [英] How can I access local variables from inside a C++11 anonymous function?

查看:62
本文介绍了如何从C ++ 11匿名函数内部访问局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对向量(权重)进行简单的归一化,试图利用STL算法使代码尽可能清晰(我意识到这对于for循环来说是微不足道的):

I'm doing a simple normalization on a vector (weights), trying to make use of STL algorithms to make the code as clean as possible (I realize this is pretty trivial with for loops):

float tot = std::accumulate(weights.begin(), weights.end(), 0.0);
std::transform(weights.begin(), weights.end(), [](float x)->float{return(x/tot);});

目前,匿名函数不可见tot,因此无法编译.使局部变量对匿名函数可见的最佳方法是什么?

At present, tot is not visible to the anonymous function, so this doesn't compile. What's the best way of making a local variable visible to the anonymous function?

推荐答案

您需要关闭.

float tot = std::accumulate(weights.begin(), weights.end(), 0);
std::transform(weights.begin(), weights.end(), [tot](float x)->float{return(x/tot);});

在这种情况下,tot被值捕获. C ++ 11 lambdas支持通过以下方式捕获:

In this case tot is captured by value. C++11 lambdas support capturing by:

  1. [x]
  2. 参考[&x]
  3. 通过引用[&]当前在范围内的任何变量
  4. 与3相同,但按值[=]
  1. value [x]
  2. reference [&x]
  3. any variable currently in scope by reference [&]
  4. same as 3, but by value [=]

您可以在逗号分隔的列表[x, &y]中混合以上任何内容.

You can mix any of the above in a comma separated list [x, &y].

这篇关于如何从C ++ 11匿名函数内部访问局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆