Creating 2D array by different ways?
// 1) Simple One to Create 2D array
int arr[3][2]={{1,2},
{3,4},
{5,6}};
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
// Output
1 2
3 4
5 6
And we have some other method to do the same things
2) Other Methods - * Double Pointer *
int n=3,m=2;
// The pointer arr is pointing to the new int of size n
int **arr;
arr= new int *[n]; // int **arr = new int *[n]
for (int i = 0; i < n; i++)
{
arr[i] = new int [m];
} // after this loop our 2d array is Created of n*m
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
arr[i][j]=28;
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
// Output
28 28
28 28
28 28
3). Other Methods - * Array Vector *
3) Other Methods - * Array Vector *
int n=3,m=2;
vector<int> arr[n]; //arr is the array of vectors of int of size n
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
arr[i].push_back(56);
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
// output
56 56
56 56
56 56
4) Other Method Vector of Vector
// 4) Other Method - Vector of Vector
int n=3,m=2;
vector<vector<int> > arr;
for (int i = 0; i < n; i++)
{
vector<int> v;
for (int i = 0; i < m; i++)
{
v.push_back(128);
}
arr.push_back(v);
}
for (int i = 0; i <arr.size(); i++)
{
for (int j = 0; j <m; j++)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
// Output
128 128
128 128
128 128
Thank You for reading this ❤️