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


excuse me, i'm new in stl in c++. how can initialize array of 10 vector pointer each of points vector of 5 int elements.

my code snippet follows:

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

thanks

this creates vector containing 10 vector<int>, each 1 of 5 elements:

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

note if size of outer container fixed, might want use std::array instead. note initialization 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 contents of array part of array. it's size, given sizeof, larger vector version, , there no o(1) move or swap operation available. std::array akin fixed size, automatic storage plain array.

note that, @chris suggests in comments, can chose set elements of array after default initialization, e.g. std::fill if have same value:

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

otherwise, can set/modify individual elements:

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

and on.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -