Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-dimensional vector

Tags:

c++

vector

vector<vector<int> > a;

If you want to define the rows and columns,

vector<vector<int> > a{{11, 2, 4}, {4, 5, 6}, {10, 8, -12}};


std::vector< std::vector< int > > a; // as Ari pointed

Using this for a growing matrix can become complex, as the system will not guarantee that all internal vectors are of the same size. Whenever you grow on the second dimension you will have to explicitly grow all vectors.

// grow twice in the first dimension
a.push_back( vector<int>() );
a.push_back( vector<int>() );

a[0].push_back( 5 ); // a[0].size() == 1, a[1].size()==0

If that is fine with you (it is not really a matrix but a vector of vectors), you should be fine. Else you will need to put extra care to keep the second dimension stable across all the vectors.

If you are planing on a fixed size matrix, then you should consider encapsulating in a class and overriding operator() instead of providing the double array syntax. Read the C++ FAQ regarding this here


std::vector< std::vector<int> > a;

    //m * n is the size of the matrix

    int m = 2, n = 4;
    //Grow rows by m
    a.resize(m);
    for(int i = 0 ; i < m ; ++i)
    {
        //Grow Columns by n
        a[i].resize(n);
    }
    //Now you have matrix m*n with default values

    //you can use the Matrix, now
    a[1][0]=98;
    a[1][1]=989;
    a[1][2]=981;
    a[1][3]=987;

//OR
for(i = 0 ; i < m ; ++i)
{
    for(int j = 0 ; j < n ; ++j)
    {      //modify matrix
        int x = a[i][j];
    }

}

If you don't have to use vectors, you may want to try Boost.Multi_array. Here is a link to a short example.


Declaration of a matrix, for example, with 5 rows and 3 columns:

vector<vector<int> > new_matrix(5,vector<int>(3));

Another way of declaration to get the same result as above:

vector<int> Row;    

One row of the matrix:

vector<Row> My_matrix;

My_matrix is a vector of rows:

My_matrix new_matrix(5,Row(3));