How to initialize an array of vector in C++ w

2020-03-12 05:49发布

问题:

Excuse me, I'm new in STL in C++. How can I initialize an array of 10 vector pointer each of which points to a vector of 5 int elements.

My code snippet is as follows:

vector<int>* neighbors = new vector<int>(5)[10];  // Error

Thanks

回答1:

This creates a vector containing 10 vector<int>, each one of those with 5 elements:

std::vector<std::vector<int>> v(10, std::vector<int>(5));

Note that if the size of the outer container is fixed, you might want to use an std::array instead. Note the initialization is more verbose:

std::array<std::vector<int>, 10> v{{std::vector<int>(5), 
                                    std::vector<int>(5), 
                                    std::vector<int>(5), 
                                    std::vector<int>(5), 
                                    std::vector<int>(5),
                                    std::vector<int>(5), 
                                    std::vector<int>(5), 
                                    std::vector<int>(5), 
                                    std::vector<int>(5), 
                                    std::vector<int>(5)
                                    }};

Also note that the contents of array are part of the array. It's size, as given by sizeof, is larger than the vector version, and there is no O(1) move or swap operation available. An std::array is akin to a fixed size, automatic storage plain array.

Note also that, as @chris suggests in the comments, you can chose to set the elements of the array after a default initialization, e.g. with std::fill if they are all to have the same value:

std::array<std::vector<int>, 10> v; // default construction
std::fill(v.begin(), v.end(), std::vector<int>(5));

otherwise, you can set/modify the individual elements:

v[0] = std::vector<int>(5); // replace default constructed vector with size 5 one
v[1].resize(42); // resize default constructed vector to 42

and so on.