初始化 vector<doubles> c++ 的向量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7519215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:03:46  来源:igfitidea点击:

initializing a vector of vector<doubles> c++

c++vector

提问by smilingbuddha

Hi I want to initialize a size 9 vector whose elements are vectors of the size, say 5. I want to initialize all the elements to the zero vector.

嗨,我想初始化一个大小为 9 的向量,其元素是大小的向量,比如 5。我想将所有元素初始化为零向量。

Is this way correct?

这种方式正确吗?

vector<double> z(5,0);

vector< vector<double> > diff(9, z);

OR is there a shorter way to do this?

或者有没有更短的方法来做到这一点?

回答by bdonlan

You could potentially do this in a single line:

您可以在一行中完成此操作:

vector<vector<double> > diff(9, vector<double>(5));

You might also want to consider using boost::multi_arrayfor more efficient storage and access (it avoids double pointer indirection).

您可能还想考虑使用boost::multi_array来提高存储和访问效率(它避免了双指针间接访问)。

回答by Kerrek SB

You can put it all in one line:

您可以将所有内容放在一行中:

vector<vector<double>> diff(9, vector<double>(5));

This avoids the unused local variable.

这避免了未使用的局部变量。

(In pre-C++11 compilers you need to leave a space, > >.)

(在 C++11 之前的编译器中,您需要留一个空格,> >.)

回答by Mark B

vector< vector<double> > diff(9, std::vector<double>(5, 0));

vector< vector<double> > diff(9, std::vector<double>(5, 0));

However in the specific case where the sizes are known at compile time you coulduse a C array:

但是,在编译时已知大小的特定情况下,您可以使用 C 数组:

double diff[9][5] = { { 0 } };

double diff[9][5] = { { 0 } };

回答by R. Martinho Fernandes

If the sizes are fixed, you can go with std::arrayinstead:

如果尺寸是固定的,您可以std::array改为:

std::array<std::array<double,5>,9> diff = {};

回答by riwalk

Pretty sure this will work:

很确定这会起作用:

vector< vector<double> > diff(9, vector<double>(5,0));