Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use algorithms to fill vector of vectors

I have

typedef std::vector<int> IVec;
typedef std::vector<IVec> IMat;

and I would like to know how I can fill an IMat by using std algorithms, ie how to do the following with less code (all the IVecs have the same size) ?

void fill(IMat& mat){
    for (int i=0;i<mat.size();i++){
        for (int j=0;j<mat[i].size();j++){
            mat[i][j] = i*j;
        }
    }
}

PS: already a way to fill the matrix with a constant would help me. And preferably with pre-C++11 algorithms.

like image 356
463035818_is_not_a_number Avatar asked Oct 22 '15 11:10

463035818_is_not_a_number


People also ask

What is vector fill?

Fill enables you to: select an register, bit operand, or constant value, define a vector of operands, write the selected value into every operand within the vector.


1 Answers

The best solution is the one that you have already implemented. It takes advantage of using i/j as both offsets and as inputs to compute the algorithm.

Standard algorithms will have to use iterators for the elements and maintain counters. This data mirroring as a sure sign of a problem. But it can be done, even on one line if you wanna be fancy:

for_each(mat.begin(), mat.end(), [&](auto& i) { static auto row = 0; auto column = 0; generate(i.begin(), i.end(), [&]() { return row * column++; }); ++row; });

But as stated just cause it could be done doesn't mean that it should be done. The best way to approach this is the for-loop. Even doing it on one line is possible if that's your thing:

for(auto i = 0U;i < mat.size();i++) for(auto j = 0U;j < mat[i].size();j++) mat[i][j] = i*j;

Incidentally my standard algorithm works fine on Clang 3.7.0, gcc 5.1, and on Visual Studio 2015. However previously I used transform rather than generate. And there seem to be some implementation bugs in gcc 5.1 and Visual Studio 2015 with the captures of lambda scope static variables.

like image 146
Jonathan Mee Avatar answered Nov 04 '22 12:11

Jonathan Mee