Search code examples
c++stdvector

is initializing an n-dimensional vector with constructor bad?


So, I recently figured out, that we can initialize an n sized vector with default values by writing e.g. vector<int> x(n, default_value).

This can also be applied to n dimensional vectors, e.g. n=3:

vector<vector<vector<int>>> x(n, vector(n, vector(n, default_value)))

Has this approach any advantages or disadvantages over doing:

vector<vector<vector<int>>> x;
x.resize(n);
for (int i = 0; i < n; i++)
{
    x[i].resize(n);
    for (int j = 0; j < n; j++)
    {
        x[i][j].resize(n);
    }
}

Solution

  • The first one first creates default_value for each vector and then copies it to the destinations, so you get (n+1)^k allocations instead of n^k.

    You forgot to initialize the integer-based vector. Therefore I argue the first version is less error-prone ;) It's also much cleaner and shows the intention clearly.

    Although second could benefit from for(auto& c:vec) loops instead of indices. Or std::for_each, or any other loop-hiding stuff... Anyway you are doing initialization -> just use constructors.