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

前端 未结 3 1169
南笙
南笙 2021-01-04 19:16

I have a 2D char vector:

vector< vector > matrix;

I will read in a matrix as an input and store it in that v

相关标签:
3条回答
  • 2021-01-04 19:57

    While construction with sized vector as default value, given by @leemes, is quite an answer, there is an alternative without using an additional vector and copy ctor:

    assert(COL >= 0);
    assert(ROW >= 0);
    vector<vector<char>> matrix;
    for (size_t i{0}; i != COL; ++i)
    {
        matrix.emplace_back(ROW);
    }
    
    0 讨论(0)
  • 2021-01-04 19:59
        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;
    
    0 讨论(0)
  • 2021-01-04 20:16

    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].

    0 讨论(0)
提交回复
热议问题