问题
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.
回答1:
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>() );
}
);
回答2:
If you don't have lambdas available to you, you could implement a functor to transform each vector<double>
:
struct transformer
{
transformer(vector<double>& s)
:s_(s)
{
}
vector<double>& operator ()(vector<double>& v)
{
transform(v.begin(), v.end(), s_.begin(), v.begin(), plus<double>());
return v;
}
vector<double> s_;
};
And use this in your call to transform
for your vector
of vector<double>
:
transform(data.begin(), data.end(), data.begin(), transformer(scalars));
来源:https://stackoverflow.com/questions/15014686/stdtransform-for-a-vector-of-vectors