Create N-Dimensional Vector with Preset Values in C++


14 Jan 2016 cpp

A simple 2D vector can be initialized with preset values using fill constructor.

int xdim = 5;
int ydim = 4;

vector<vector<string> > container(xdim, vector<string>(ydim, "1"));

for(int x=0; x<xdim; x++)
{
    for(int y=0; y<ydim; y++)
    {
        cout << container[x][y] << " ";
    }
    cout << endl;
}

This will result in a 5x4 vector of strings with “1” in each cell.

1 1 1 1 
1 1 1 1 
1 1 1 1 
1 1 1 1 
1 1 1 1 

Similarly, a 3D vector can also be initialized like the following.

int xdim = 5;
int ydim = 4;
int zdim = 3;

vector<vector<vector<string> > > container(
            xdim, vector<vector<string> >(
                ydim, vector<string>(zdim, "0")
                )
            );

for(int x=0; x<xdim; x++)
{
    for(int y=0; y<ydim; y++)
    {
        cout << "[";
        for(int z=0; z<zdim; z++)
        {
            cout << container[x][y][z];
        }
        cout <<"] ";
    }
    cout << endl;
}

This will result in a 5x4x3 vector of strings with “0” in each cell.

[000] [000] [000] [000] 
[000] [000] [000] [000] 
[000] [000] [000] [000] 
[000] [000] [000] [000] 
[000] [000] [000] [000]