1

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?

gramos
  • 67
  • 1
  • 11
  • Possible duplicate of [What is a lambda expression in C++11?](http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11) – LogicStuff Jun 27 '16 at 18:23
  • 2
    `randomFloat() * 2 - 1.0 / Math.sqrt(maxNumSource);` should be `(randomFloat() * 2 - 1.0) / Math.sqrt(maxNumSource);` to match the the C++ code. – NathanOliver Jun 27 '16 at 18:24
  • @NathanOliver you're right. Precedence. But my main concern is about the weight variable. Where is it going? – gramos Jun 27 '16 at 18:27
  • 2
    You should generally avoid the class version of the primitive data types (Integer, Double) and just use the simple data types directly (int, double). Only use the class version if there is a specific need for it. – Jan Henke Jun 27 '16 at 18:27
  • 2
    I'm not sure where that `Vector` is coming from but if it is your code, consider dropping it and [using an `ArrayList` instead](http://stackoverflow.com/questions/1386275/why-is-java-vector-class-considered-obsolete-or-deprecated). – Tunaki Jun 27 '16 at 18:32
  • @JanHenke OK. Thanks. – gramos Jun 27 '16 at 18:34
  • @Tunaki The C++ code is using Vector everywhere. Still don't know the impact of chaging everything to List, but I will assess that. Thanks. – gramos Jun 27 '16 at 18:34

1 Answers1

3

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'
Rakete1111
  • 47,013
  • 16
  • 123
  • 162