Creating two-dimensional arrays with vectors in the STL

Source: Internet
Author: User
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
*/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.