Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an array of vector<int> in C++ with predefined counts?

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

like image 751
remo Avatar asked Aug 10 '13 07:08

remo


1 Answers

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.

like image 163
juanchopanza Avatar answered Oct 04 '22 00:10

juanchopanza