How to resize a C ++ 2D vector?

I have a 2D vector char:

vector< vector<char> > matrix;

I will read in the matrix as input and save it in this vector. The size of my vector is fixed and equal to ROW x COL. I think I need to resize it for each row and column.

How can I execute it without taking extra memory (changing it correctly)?

+4
source share
2 answers

If the vector is empty , you can simply change the external vector with previously selected internal vectors without the need for a loop:

matrix.resize(COL, vector<char>(ROW));

, reset a , :

matrix = vector<vector<char> >(COL, vector<char>(ROW));

, , ROW COL. ( ) - , , matrix[col][row].

+12
    const size_t ROW = 10;
    const size_t COL = 20;
    std::vector<std::vector<char>> v;

    v.resize( ROW );

    std::for_each( v.begin(), v.end(), 
                   std::bind2nd( std::mem_fun_ref( &std::vector<char>::resize ), COL ) );

    std::cout << "size = " << v.size() << std::endl;
    for ( const std::vector<char> &v1 : v ) std::cout << v1.size() << ' ';
    std::cout << std::endl;
+1

All Articles