Multi-dimensional vector

后端 未结 8 2107
一个人的身影
一个人的身影 2020-11-28 09:32

How can I create a 2D vector? I know that in 2D array, I can express it like:

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]         


        
8条回答
  •  时光说笑
    2020-11-28 09:43

    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() );
    a.push_back( vector() );
    
    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

提交回复
热议问题