using STL vector to create two-dimensional arrays
I used to build a two-dimensional array, always using the
int n=5, m=6;
vector<vector<int> > Matrix (N);
for (int i =0; i< matrix.size (); i++) {
Matrix[i].resize (M);
}
There are three more lines written above to specify the number of the Matrix.
We found out today that we can do the work in a simpler way.
The following line can replace the four lines above
vector<vector<int> > Matrix (N, vector<int> (M));
/*
* =====================================================================================
*
* Filename:2d.cpp
*
* Description: How to build a two-dimensional array
*
* =====================================================================================
*/
#include <vector>
#include <iostream>
#include <iterator>
using namespace Std;
int main () {
int n=2,m=3;
vector<vector<int> > Matrix (N, vector<int> (m,-1));
ostream_iterator<int> OS (cout, "");
matrix[0][2]=4;
Two rows of a commutative matrix
Matrix[0].swap (matrix[1]);
Two elements in the second row of the interchange matrix
Swap (matrix[1][0],matrix[1][2]);
for (int i=0;i<matrix.size (); i++) {
Copy (Matrix[i].begin (), Matrix[i].end (), OS);
cout<<endl;
}
return exit_success;
}
/** Output Results
*
tlu:stl$ g++-o 2d.exe 2d.cpp
tlu:stl$./2d.exe
-1-1-1
-1-1 4
*/