c++ - 用迭代器计算矩阵 vector<vector<double>> 的列和?

标签 c++ vector stl mean accumulate

在之前的帖子中 column vector with row means -- with std::accumulate?我问是否有可能使用 STL 功能来计算矩阵的行均值

vector< vector<double> > data ( rows, vector<double> ( columns ) );

@benjaminlindley 的最佳答案不仅是我一直在寻找的,而且是一件美丽的事情。永远充满希望我认为计算列均值会很容易,所以 STL 等价于

vector<double> colmeans( data[0].size() );
    for ( int i=0; i<data.size(); i++ )
        for ( int j=0; j<data[i].size(); j++ )            
            colmeans[j] += data[i][j]/data.size();

在每个 vector<double> 中不计算平均值,但跨所有 vector 中的相同索引:

colmeans[0]       == ( data[0][0] + data[1][0] + ... data[rows][0] ) / rows
colmeans[1]       == ( data[0][1] + data[1][1] + ... data[rows][1] ) / rows
colmeans[2]       == ( data[0][2] + data[1][2] + ... data[rows][2] ) / rows
...
colmeans[columns] == ( data[0]   [columns] + 
                       data[1]   [columns] + 
                       ... 
                       data[rows][columns] ) / rows

结果完全不同——accumulate 不想处理 vector 的 vector 。是否有可能将 accumulate 与 [] 一起使用?运算符(operator)?我什至无法想出一个看起来不正确的中间形式(以摆脱 for ifor j 循环)。

带有 accumulate 的东西和 []运算符(operator)?或者 bind

最佳答案

这是我使用 for_eachtransform 想出的东西:

std::vector<std::vector<double>> data { {1,2,3}, {1,2,3}, {1,2,3} };

std::vector<double> colsums( data[0].size() ); // initialize the size
                                                // to number of columns

std::for_each(data.begin(), data.end(),

    [&](const std::vector<double>& row)
    {
        // Use transform overload that takes two input ranges.
        // Note that colsums is the second input range as well as the output range.
        // We take each element of the row and add it to the corresponding
        // element of colsums vector:
        std::transform(row.begin(), row.end(), colsums.begin(), colsums.begin(),
                       [](double d1, double d2) { return d1 + d2; });
    });

std::cout << "Column means: ";
std::transform(
    colsums.begin(), colsums.end(),
    std::ostream_iterator<double>(std::cout, " "),
    [&data](double d) { return d / data.size(); });

LWS Demo

关于c++ - 用迭代器计算矩阵 vector<vector<double>> 的列和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14924912/

相关文章:

c++ - 从 ">"运算符导出 "<"运算符

c++ - 构建动态大小的 std::initializer_list,第二部分

c++ - 为哈希表初始化 STL 列表的动态数组(单独链接)

c++ - 如何在带有输入的 map 元素方法上使用 std::for_each?

c++ - 类和文件阅读

c++ - 从 .c 文件调用 .cpp 文件中的函数

c++ - Armadillo C++ : Efficient and concise way to multiply every row of a matrix by a vector?

c++ - 使用具有自定义比较类型的关联容器的问题

c++ - 是否有适用于 Windows 的 iTunes C++ 库允许访问 USB 连接的 iOS 设备的文件系统?

c++ - 获取 vector 的内容并将它们放入文本文件中