How to rewrite a nested loop using the C++ STL algorithms?

use*_*386 10 c++ algorithm for-loop stl vector

The loop is simple enough, but I just can't seem to wrap my head around using the STL algorithms to give the same nested loop below.

const int a_size = 5; // input
const int c_size = 2; // output
const int b_size = a_size * c_size; // multipliers

std::vector<float> a(a_size);
std::vector<float> b(b_size);
std::vector<float> c(c_size);

// fill a and b with data

// this nested loop
for(int i = 0; i<c_size; i++) {
    c[i] = 0.0;
    for(int k = 0; k<a_size; k++) {
        c[i] += (a[k] * b[i*a_size+k]);
    }
    c[i] = sigmoid(c[i]);
}
Run Code Online (Sandbox Code Playgroud)

The reason why I would like to do this, is for the Boost.Compute library, which would do the calculations on the GPU using STL-like algorithms (std::transform, std::for_each, etc.).

Vla*_*cow 8

事实上,嵌套循环是算法std :: inner_product.

auto first = std::begin( b );
auto increment = std::distance( std::begin( a ), std::end( a ) );
//,,

c[i] = std::inner_product( std::begin( a ), std::end( a ), first, 0 );
std::advance( first, increment );
Run Code Online (Sandbox Code Playgroud)

您可以使用算法std :: generate代替外部循环.


Evg*_*yuk 6

我想出了:

auto i = 0;
generate(begin(c), end(c), [&i, &a, &b]
{
    return sigmoid(inner_product
    (
        begin(a), end(a),
        begin(b) + distance(begin(a), end(a)) * i++, 0.f
    ));
});
Run Code Online (Sandbox Code Playgroud)

但它看起来不太好 - 可能在这种情况下我宁愿编写自己的算法.

或者使用矩阵形式.随着Eigen图书馆,它将成为:

MatrixXd b;
VectorXd a, c;
// ...
c = (b*a).unaryExpr(sigmoid);
Run Code Online (Sandbox Code Playgroud)

  • @nijansen据我所知[code-sample](http://glm.g-truc.net/0.9.4/code.html) - 它只提供类似于GLSL for C++的类型,但不提供GPU上的计算. (3认同)