Jim
Jim

Reputation: 327

Initialize a vector of vectors where not all vectors are of same size C++

I have some data like this.

static const double v1_arr={2,3,4}
vector<double> v1_vec(v1_arr, v1_arr + sizeof(v1_arr[0]))

static const double v2_arr={9,6}
vector<double> v2_vec(v2_arr, v2_arr + sizeof(v2_arr[0]))

static const double v3_arr={9,6,7,6}
vector<double> v3_vec(v3_arr, v3_arr + sizeof(v3_arr[0]))

How do I initialize a vector of vectors v_v which contains the three above vectors?

Upvotes: 0

Views: 71

Answers (2)

juanchopanza
juanchopanza

Reputation: 227628

You can use a brace enclosed initializer:

vector<vector<double>> v_3{v1_vec, v2_vec, v3_vec};

Unless you need the "arrays" and `vector objects (assuming you fix the syntax errors to actually declare some arrays) the whole thing can be simplified to

vector<vector<double>> v_3{{2, 3, 4}, {9, 6}, {9, 6, 7, 6}};

Upvotes: 3

toth
toth

Reputation: 2552

If you are using a compiler that supports C++11 you can simply do

vector<vector<double>> v_3{v1_vec, v2_vec, v3_vec};

If not you will have to do something like

vector<vector<double>> v_3;
v_3.push_back(v1_vec);
v_3.push_back(v2_vec);
v_3.push_back(v3_vec);

Note that if you can use C++11 features, you can simply initialize your other vectors like this

vector<double> v1_vec{1.0, 2.0, 3.0};

and skip the intermediate v1_arr.

Upvotes: 4

Related Questions