# Initialize 3D vector in C++

This article shows how we can initialize 2D, 3D or any Dimension vector in C++ .

##### Syntax to Initialize 1D vector
vector<int> v(n);

The above code declares a 1D vector of size n.

vector<int> v(n, X);

The above code initialize a 1D vector of size n, all positions filled with value X.

##### Syntax to Initialize a 2D vectors
vector< vector<int> > v( n ,vector<int>(m) );

The above code initialize a 2D vector of size n x m.

Example,

#include<iostream>
#include<vector>
using namespace std;

int main(){

int n,m;
n = 4;
m = 5;

vector<vector<int> > v(n,vector<int>(m));

for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
v[i][j] = i*m + j;
}
}

cout<<"Content of 2D Vector: "<<endl;
for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
cout<<v[i][j]<<' ';
}
cout<<endl;
}

return 0;
}

Output

##### Syntax to Initialize 2D vector with same value
vector< vector<int> > v( n, vector<int>(m, X) );

The above code initialize the 2D vector of size n x m and fill all positions with value X.

Example,

#include<iostream>
#include<vector>
using namespace std;

int main(){

int n,m;
n = 4;
m = 5;

vector<vector<int> > v(n,vector<int>(m , 0));

cout<<"Content of 2D Vector: "<<endl;
for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
cout<<v[i][j]<<' ';
}
cout<<endl;
}

return 0;
}

Output

##### Syntax to Initialize 3D vector
vector< vector< vector<int> > > v(n , vector< vector<int> > (m, vector<int> (l) ) );

The above code initialize a 3D vector of size n x m x l.

Example,

#include<iostream>
#include<vector>
using namespace std;

int main(){

int n,m,l;
n = 2;
m = 5;
l = 4;

vector< vector< vector<int> > > v(n, vector< vector<int> >(m , vector<int>(l)));

for(int i=0;i<n;++i){
for(int j=0;j<m;++j){
for(int k=0;k<l;++k){
v[i][j][k] = i*m*l + j*l + k;
}
}
}

cout<<"Content of 3D Vector: "<<endl;
for(int i=0;i<n;++i){
for(int j=0;j<m;++j){
for(int k=0;k<l;++k){
cout<<v[i][j][k]<<' ';
}
cout<<endl;
}
cout<<endl;
}

return 0;
}

Output

##### Syntax to Initialize 3D vector with same value
vector< vector< vector<int> > > v(n , vector< vector<int> > (m, vector<int> (l, X) ) );

The above code initialize a 3D vector of size n x m x l filled with value X.

Example,

#include<iostream>
#include<vector>
using namespace std;

int main(){

int n,m,l;
n = 2;
m = 5;
l = 4;

vector< vector< vector<int> > > v(n, vector< vector<int> >(m , vector<int>(l, 1)));

cout<<"Content of 3D Vector: "<<endl;
for(int i=0;i<n;++i){
for(int j=0;j<m;++j){
for(int k=0;k<l;++k){
cout<<v[i][j][k]<<' ';
}
cout<<endl;
}
cout<<endl;
}

return 0;
}

Output