简体   繁体   中英

Is there a way to declare an array of std::vector of a certain size?

I want to declare an array of vectors of a certain length. To declare an array of vectors, I write this, for instance:

std::vector<double> myarray[17][38][42];

This creates a 3-dimensional 17x38x24 array, where each element is of type std::vector<double> .

I also know that to specify the size of a std::vector I may write, for instance:

std::vector<double> myvector(14);

This creates a std::vector with space allocated for 14 elements.

I run into a problem when I try to combine these two procedures. For example, writing:

std::vector<double> myarray[17][38][42](14);

I receive this error:

error: array must be initialized with a brace-enclosed initializer [-fpermissive]
std::vector<double> myarray[17][38]42;

When I try to initialize it this way:

std::vector<double> myotherarray(14)[17][38][42];

I receive this error:

error: expected ',' or ';' before '[' token
std::vector<double> myotherarray(14)[17][38][42];

What is the proper way to declare every element of the array to be a std::vector of a certain size?

You have an array of (array of array of) vectors, so if you want to inialize it, you have to use brace initializer list, and you have to initialize each vector element (effectively 38* 42 * 14 vectors.) explicitly. This doesn't seem feasible.

If you only want to initialize the very first vector in the array (of arrays of arrays) (or a very few vectors) you can do this:

std::vector<double> vec[17][38][42]{{{std::vector<double>(14)}}};

But from practical standpoint, you'd have to iterate over those arrays of vectors in a loop and resize them.

You can't initialize such a multi-dimensional array the way you want. But you can declare it first and then use a separate initialization loop instead, eg:

std::vector<double> myarray[17][38][42];
for(size_t i = 0; i < 17; ++i) {
    for(size_t j = 0; j < 38; ++j) {
        for(size_t k = 0; k < 42; ++k) {
            myarray[i][j][k].resize(14);
        }
    }
}

Or:

std::vector<double> myarray[17][38][42];
for(auto &d1 : myarray) {
    for(auto &d2 : d1) {
        for(auto &elem : d2) {
            elem.resize(14);
        }
    }
}

But, if you already know the vector size at compile-time, why use std::vector at all? You can use std::array instead, eg:

std::array<double, 14> myarray[17][38][42];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM