Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading