all*_*ije 6 c++ stl vector mean accumulate
在前一个带有行意味着的列后向量中 - 使用std :: accumulate?我问是否有可能使用STL功能来计算矩阵的行方式
vector< vector<double> > data ( rows, vector<double> ( columns ) );
Run Code Online (Sandbox Code Playgroud)
@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();
Run Code Online (Sandbox Code Playgroud)
其中均值不是在每个内部计算的vector<double>,而是在所有向量中的相同索引中计算:
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
Run Code Online (Sandbox Code Playgroud)
事实证明它是完全不同的 - 累积不想对矢量矢量起作用.是否可以使用累积与[]运算符?我甚至无法想出一个似乎不对的中间形式(摆脱for i或者for j循环).
一些与accumulate和[]操作?还是bind?
这是我想出来的,使用for_each和transform:
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(); });
Run Code Online (Sandbox Code Playgroud)