tags:

views:

329

answers:

7

Hai C++

How to create a 2D vector where in like 2D array

a[0][1]=98;
a[0][2]=95;
a[0][3]=99;
a[0][4]=910;

a[1][0]=98;
a[1][1]=989;
a[1][2]=981;
a[1][3]=987;

how do the same in vector? Thank you in advance.

+8  A: 

vector<vector<int> > a;

Ari
+4  A: 
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 lite here

David Rodríguez - dribeas
+2  A: 
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];
    }

}
aJ
A: 

Note the space after "<int>" in previous answers:

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

It will be not needed in C++0x.

A: 

dribeas' suggestion is really the way to go.

Just to give a reason why you might want to go the operator() route, consider that for instance if your data is sparse you can lay it out differently to save space internally and operator() hides that internal implementation issue from your end user giving you better encapsulation and allowing you to make space or speed improving changes to the internal layout later on without breaking your interface.

Robert S. Barnes
+4  A: 

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

Benoît
A: 

As Ari pointed, vector< vector< int>> is the right way to do it.

In addition to that, in such cases I always consider wrapping the inner vector (actually, whatever it represents) in a class, because complex STL structures tend to become clumsy and confusing.

Igor Oks