If each element of a vector is a vector, it is called a two-dimensional vector, for example
Vector <vector <int> VV (3, vector <int> (4); // here, spaces between two ">" are indispensable.
A two-dimensional vector VV is constructed, which contains three elements. Each element contains a vector of four int elements. The compiler calls the vector constructor twice to construct the object VV. The first call constructor constructs an unknown vector containing four zeros <int> object:
The second call to the constructor initializes three elements of the constructor with the unknown vector as the initial value. The result is:
VV |
[0] |
[1] |
[2] |
[3] |
[0] |
0 |
0 |
0 |
0 |
[1] |
0 |
0 |
0 |
0 |
[2] |
0 |
0 |
0 |
0 |
VV [I] indicates a vector composed of elements in the I (I =, 2) rows. Vv. Size () is 3, VV [1]. Size () is 4.
The length of each element in a two-dimensional vector can be different, for example
vector<vector<int> >vv;for(int c = 1; c <= 3; c++)vv.push_back(vector<int>(c,0));
The code above generates a two-dimensional vector with different lengths. The first row has only one element, the second row has two, and the third row has three elements.
Example: Enter n integers and divide them by the selected integers (called modulus). The integers are grouped by the remainder.
# Include <iostream> # include <vector> using namespace STD; void classify (vector <int> & V, int mode, vector <int> & vv) {for (vector <int >:: const_iterator iter = v. begin (); iter! = V. end (); ITER ++) {int Index = (* ITER) % mode; // obtain the remainder VV [Index]. push_back (* ITER); // insert element} int main () {int mode; // mode CIN> mode; vector <int> VV (mode ); // defines a two-dimensional vector int N with mode rows; // n integers CIN> N; vector <int> V (n); // One-dimensional vector, save n integers for (INT I = 0; I <n; I ++) CIN> V [I]; // start classify (v, mode, vv ); for (I = 0; I <mode; I ++) {cout <"remainder is" <I <":"; if (VV [I]. empty () cout <Endl; else {for (vector <int>: const_iterator P = VV [I]. B Egin (); P! = VV [I]. End (); P ++) cout <* P <""; cout <Endl ;}} return 0 ;}
Running result: