c++ - 如何使用 C++ STL 算法重写嵌套循环?

标签 c++ algorithm for-loop vector stl

循环很简单,但我似乎无法使用 STL 算法来给出下面相同的嵌套循环。

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

我想这样做的原因是为了 Boost.Compute 库,它会使用类似 STL 的算法(std::transform、std::for_each 等)在 GPU 上进行计算。

最佳答案

事实上,嵌套循环是算法 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 );

您可以使用算法 std::generate 而不是外部循环。

关于c++ - 如何使用 C++ STL 算法重写嵌套循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19678144/

相关文章:

c++ - 如何标准化数字序列?

python - 递归正则表达式模式 - 在 python 中

javascript - 如果我们正在循环访问当前项目,哪个 for/forEach 的性能更高?

将函数转换为使用迭代

c++ - OpenCV:如何在文件中存储描述符?

c++ - MinGW g++ 在 powershell 中不创建输出

c++ - 无方法抽象类?

performance - 计算子集的唯一交集

algorithm - 计算最佳毛坯长度

r - 如何创建一个新列表,其中包含 R 中旧列表中的每个单独的矩阵列?