Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I resize a 2D C++ vector?

Tags:

c++

vector

resize

I have a 2D char vector:

vector< vector<char> > matrix;

I will read in a matrix as an input and store it in that vector. The size of my vector is fixed and is ROW x COL. I guess I need to resize it for each row and column.

How can I accomplish it without taking extra memory (resizing it correctly)?

like image 544
user2878007 Avatar asked Nov 18 '13 12:11

user2878007


2 Answers

Given the vector is empty, you can simply resize the outer vector with preallocated inner vectors without the need of a loop:

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

Alternatively, when initializing or if you want to reset a non-empty vector, you can use the constructor overload taking a size and initial value to initialize all the inner vectors:

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

Depending on whether your matrix is column- or row-major, you need to swap the arguments ROW and COL. The first one (the first parameter on the outer vector) is your first dimension to access the matrix, i.e. I assumed you access it with matrix[col][row].

like image 111
leemes Avatar answered Oct 13 '22 21:10

leemes


    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;
like image 36
Vlad from Moscow Avatar answered Oct 13 '22 19:10

Vlad from Moscow