简体   繁体   English

初始化向量的向量,其中并非所有向量的大小都相同

[英]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? 如何初始化包含上述三个向量的向量v_v向量?

If you are using a compiler that supports C++11 you can simply do 如果您使用的是支持C++11的编译器,则只需执行

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 请注意,如果您可以使用C++11功能,则可以像这样简单地初始化其他向量

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

and skip the intermediate v1_arr . 并跳过中间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}};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM