About two-dimensional dynamic array initialization vector

       Many times, we want to use a dynamic array to store the outset when an unknown number of data, often get the number of rows and columns in the program, and then initialize the array. However, if we only knew a number of rows or columns which can be dynamic array is initialized it?

       The answer is yes. If we know the number of rows, then initialization can be so written: vector <vector <type >> Name (row, vector <type> (0)). Such is the meaning: the number of rows to row, column number is zero. How that assignment to the array it? For example, it is known simply make a 3-line, but do not know the number of each two-dimensional matrix M ranks:

vector<vector<int>>M(3,vector<int>(0));//初始化M,行为3,列为0
vector<int>N(3);
for(int i=0;i<3;i++){
N.push_back(i+1);
}
for(int i=0;i<M.size();i++){
for(int j=0;j<N[i];j++){
M[i].push_back(1);
}
}

        Thus, the data in the two-dimensional array M is:

1

   1 1

      1 1 1

       The benefit of this column is to make dynamic, that is the number of columns per row may not be equal. Such initialization can not be used to pay attention to M [i] [j] = xx, assignment statements, as will be outside the bounds of the array, with only push_back, increasing the length of the column.

       If the list of known row unknown situation how to do? Very simple, put in rows and columns to store a change can be, for example, to store N points (x, y) coordinates is customary N * 2, but now 2 * N, the first row keep x, the second line memory y. Such a column can be dynamic. In fact, sometimes thinking is to convert it, are not squarely addressed the issue, but beating about the bush, there will always be miraculous.

       These are some ideas to use vector, hoping to inspire the audience. Hope there is an error correction! Thank you

Published 40 original articles · won praise 28 · views 60000 +

Guess you like

Origin blog.csdn.net/lyandgh/article/details/78522091