简体   繁体   中英

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?

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 .

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}};

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