std :: transform为向量的向量 [英] std::transform for a vector of vectors
问题描述
vector< vector< double> >数据(M,向量< double>(N));
vector< double> scalars(N);
data [0] [0] + = scalars [0];
data [0] [1] + = scalars [1];
...
data [0] [N-1] + = scalars [N-1];
data [1] [0] + = scalars [0];
data [1] [1] + = scalars [1];
...
data [1] [N-1] + = scalars [N-1];
...
data [M-1] [N-1] + = scalars [N-1]
当然,这是可能的两个for循环。我想知道如果它可以做到简单与transform,bind和plus?我试图在可能的情况下使用函子(虽然仍然使用旧的C风格的代码不习惯)。
内循环需要为矢量0 in data:
transform(data [0] .begin(),data [0] .end(),
标量[0] .begin(),
data [0] .begin(),
plus< double>())
是否可以用另一个计数器(与数据[0] ..数据[N-1]上的变换相关)替换此行中的数据[0]?
这可能是一个标准问题,但我找不到一个好的参考。
在 for_each
?
变换
std :: for_each(data.begin(),data.end(),
[& scalars](std :: vector< double>& v){
transform(v.begin(),v.end(),
scalars.begin(),
v.begin(),plus< double>());
}
);
I have numerical data in a vector< vector < double> > and need to add scalar values to them as follows:
vector <vector<double> > data ( M, vector<double>(N) );
vector <double>scalars(N);
data[0][0] += scalars[0];
data[0][1] += scalars[1];
...
data[0][N-1] += scalars[N-1];
data[1][0] += scalars[0];
data[1][1] += scalars[1];
...
data[1][N-1] += scalars[N-1];
...
data[M-1][N-1] += scalars[N-1];
Of course this is possible with two for loops. I was wondering if it can be done as simply with transform, bind and plus? I'm trying to use functors where possible (although still use old C-style code out of habit).
The inside loop would need to do this for the vector 0 in data:
transform ( data[0].begin(), data[0].end(),
scalars[0].begin(),
data[0].begin(),
plus<double>() )
Is it possible replace data[0] in this line with another counter (related to a transform on data[0]..data[N-1])? This is probably a standard problem but I could not find a good reference.
What about the following, simply wrapping your transform
in a for_each
?
std::for_each( data.begin(), data.end(),
[&scalars](std::vector<double>& v) {
transform ( v.begin(), v.end(),
scalars.begin(),
v.begin(), plus<double>() );
}
);
这篇关于std :: transform为向量的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!