There is a two-dimensional vector std::vector< std::vector < int> > vecInt1 . How to set and change the number of elements in the row and column during program execution? Those. for example, first there was a vector 10 * 6, then it became 15 * 13, and so on.

    2 answers 2

    Complementing the answer @diraria

    Yes, you need to use vector::assign , but you need to understand that the size of each internal vector can be different.

    For example, if we do this:

     #include <vector> #include <iostream> using namespace std; int main() { // пустой вектор vector<vector<int>> a; // вектор размера 7 x 5 // то есть семь строчек, каждая строчка состоит из пяти элементов a.assign(7, vector<int>(5)); // и отдельно, допустим, у третьей "строчки", мы сделаем длину 3 a[2].assign(33); cout << "число строк: " << a.size() << endl; for (size_t i = 0; i < a.size(); ++i) cout << "число элементов в " << i << "-ой строчке: " << a[i].size() << endl; return 0; } 

    That will be displayed to us:

     число элементов в 0-ой строчке: 5 число элементов в 1-ой строчке: 5 число элементов в 2-ой строчке: 33 число элементов в 3-ой строчке: 5 число элементов в 4-ой строчке: 5 число элементов в 5-ой строчке: 5 число элементов в 6-ой строчке: 5 

    Accordingly, you can change the size of the "two-dimensional" vector by N * M using the line

     a.assign(n, vector<int>(m)); 

    However, it will be filled with zeros, it will completely wipe it.

      Use vector::assign :

       a.assign(число_строк, vector<int>(число_столбцов)); 

      or with simultaneous filling of all elements with a new value:

       a.assign(число_строк, vector<int>(число_столбцов, новое_значение)); 

      Some explanations:

      • the vector class has several constructors , including:
        • vector(число_элементов) - creates a vector of the specified size, the elements are initialized by the default constructor
        • vector(число_элементов, значение) - creates a vector of the specified size and fills it with copies of the transferred value
      • There is also a vector::assign method that accepts a new number of elements and a value with which new elements will be filled.

      Well, another small example on Ideone :

       #include <vector> #include <iostream> using namespace std; int main() { // пустой вектор vector<vector<int>> a; // вектор размера 7 x 5 // то есть семь строчек, каждая строчка состоит из пяти элементов a.assign(7, vector<int>(5)); cout << "число строк: " << a.size() << endl; for (size_t i = 0; i < a.size(); ++i) cout << "число элементов в " << i << "-ой строчке: " << a[i].size() << endl; return 0; } 
      • or just vector::resize - Andrio Skur
      • @AndrioSkur, resize is generally not suitable in general - diraria