审查与lambda到Java的C for_each的移植

Review of porting a C++ for_each with Lambda to Java

本文关键字:each for lambda Java 审查      更新时间:2023-10-16

我正在尝试将C 代码移到Java。

摘要如下:

uint32_t maxNumSource = newLayer.size.x * newLayer.size.y;
for (auto &plane : newLayer.flatConvolveMatrix) {
    std::for_each(std::begin(plane), std::end(plane), [maxNumSource](float &weight) {
        weight = (float)(((randomFloat() * 2) - 1.0f) / sqrt(maxNumSource));
    });
}

flatConvolvolvematrix是Newlayer的成员,如下所示:

vector<vector<float>> flatConvolveMatrix;

我不确定在C 中如何处理"重量"变量。在for_each循环中以作为参数而进入,对吗?'[maxnumsource]''是什么意思?

到目前为止,在Java中,我想出了:

Integer maxNumSource = newLayer.size.x * newLayer.size.y;
for ( Vector<Double> plane : newLayer.flatConvolveMatrix ) {
    double weight = 0;
    for ( Double value : plane ) {
        weight += randomFloat() * 2 - 1.0 / Math.sqrt(maxNumSource);
    }
}

我的解释正确吗?

[maxNumSource]零件是lambda的捕获列表,它允许lambda在其体内使用变量maxNumSource的副本。

不,有一个错误:

C 版本修改了plane中的元素,而Java版本则没有。应该是:

for (Double value : plane)
    value = (randomFloat() * 2 - 1.0) / Math.sqrt(maxNumSource);
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^
               operator precendence :)
    ^^^^
     modifies the current 'value' in 'plane'