Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::transform for a vector of vectors

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.

like image 467
alle_meije Avatar asked Sep 20 '25 23:09

alle_meije


1 Answers

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>() );
                } 
             );
like image 173
us2012 Avatar answered Sep 22 '25 13:09

us2012