2d matrix cpp code example
Example 1: 2d array c++
int a[2][3]= {
{1, 2, 3},
{4, 5, 6}
};
cout << a[1][1];
Example 2: c++ 2D vectors
int main()
{
int row = 5;
int colom[] = { 5, 3, 4, 2, 1 };
vector<vector<int> > vec(row);
for (int i = 0; i < row; i++) {
int col;
col = colom[i];
vec[i] = vector<int>(col);
for (int j = 0; j < col; j++)
vec[i][j] = j + 1;
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < vec[i].size(); j++)
cout << vec[i][j] << " ";
cout << endl;
}
}
Example 3: get elements of 2d array c++
#include <array>
2 #include <iostream>
3
4 using namespace std;
5
6
7 const int ROWS = 2;
8 const int COLS = 3;
9
10 void printMatrix(array<array<int, COLS>, ROWS> matrix){
11
12 for (int row = 0; row < matrix.size(); ++row){
13
14 for (int col = 0; col < matrix[row].size(); ++col){
15 cout << matrix[row][col] << ' ';
16 }
17 cout << endl;
18 }
19 }
Example 4: get elements of 2d array c++
void printMatrix(array<array<int, COLS>, ROWS> matrix){
for (auto row : matrix){
for (auto element : row){
cout << element << ' ';
}
cout << endl;
}