Guilherme Ramos Guilherme Ramos - 5 months ago 24
Java Question

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

I am trying to port C++ code to Java.

The snippet goes as follows:

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));
});

}


Where flatConvolveMatrix is a member of newLayer declared as follows:

vector<vector<float>> flatConvolveMatrix;


I am not sure in the C++, how the 'weight' variable is being handled. Is going inside the for_each loop as a parameter, right?
What does the '[maxNumSource]' means?

So far, in Java I've come up with:

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);
}

}


Is my interpretation correct?

Answer

The [maxNumSource] part is the capture list of the lambda, it allows the lambda to use a copy of the variable maxNumSource in its body.

And no, there's one mistake:

The C++ version modifies the elements in plane, while the Java version does not. It should rather be:

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