如何从 C++11 匿名函数内部访问局部变量? [英] How can I access local variables from inside a C++11 anonymous function?
本文介绍了如何从 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:
- 值
[x]
- 参考
[&x]
- 当前在引用范围内的任何变量
[&]
- 与 3 相同,但按值
[=]
您可以在逗号分隔列表[x, &y]
中混合上述任何内容.
You can mix any of the above in a comma separated list [x, &y]
.
这篇关于如何从 C++11 匿名函数内部访问局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文