vector<vector<int>> as a 2D array

Vector can be used to replace one-dimensional arrays. Vector provides the operator[] function, which can be operated like an array, and it also has bounds checking and dynamically changes its size.
It is only introduced here to replace the two-dimensional array, and so on.

1. Define a two-dimensional vector

vector<vector<int>  > v;//注意>和>之间的空格。

2. Three ways to access elements of a two-dimensional vector

If you specify the size of the outer and inner vectors, you can use operator[] to read and write; if you only specify the size of the outer vector, you can use the push_back() function to write, but operator[] cannot be used to read and write.
1) Specify the size of the outer vector, which
can be initialized with the push_back function:

v.resize(3);
v[1].push_back(9);

2) Traverse the size of the specified inner vector Set the size of each line of vector in
advance , you can use operator[] to access, as follows:

for(int i=0;i<3;i++)
    v[i].resize(3);

3) Specify the size of the inner and outer layer vectors at a time

v.resize(n, vector<int>(m));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325618545&siteId=291194637