如何使用预定义的计数在 C++ 中初始化 vector<int> 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18159820/
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-27 21:46:09  来源:igfitidea点击:

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

c++arraysvectorstlinitialization

提问by remo

Excuse me, I'm new in STL in C++. How can I initialize an array of 10 vector pointer each of which points to a vector of 5 int elements.

对不起,我是 C++ 中 STL 的新手。如何初始化一个包含 10 个向量指针的数组,每个指针指向一个包含 5 个 int 元素的向量。

My code snippet is as follows:

我的代码片段如下:

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

Thanks

谢谢

回答by juanchopanza

This creates a vector containing 10 vector<int>, each one of those with 5 elements:

这将创建一个包含 10 的向量vector<int>,每个向量有 5 个元素:

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

Note that if the size of the outer container is fixed, you mightwant to use an std::arrayinstead. Note the initialization is more verbose:

请注意,如果外部容器的大小是固定的,您可能需要使用 anstd::array来代替。注意初始化更冗长:

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 that the contents of array are part of the array. It's size, as given by sizeof, is larger than the vectorversion, and there is no O(1) move or swap operation available. An std::arrayis akin to a fixed size, automatic storage plain array.

另请注意,数组的内容是数组的一部分。它的大小,由 给出sizeof,大于vector版本,并且没有 O(1) 移动或交换操作可用。Anstd::array类似于固定大小的自动存储普通数组。

Note also that, as @chris suggests in the comments, you can chose to set the elements of the array aftera default initialization, e.g. with std::fillif they are all to have the same value:

另请注意,正如@chris 在评论中建议的那样,您可以选择默认初始化设置数组的元素,例如,std::fill如果它们都具有相同的值:

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

otherwise, you can set/modify the individual elements:

否则,您可以设置/修改单个元素:

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

and so on.

等等。