如何初始化矢量&lt阵列; INT>在C ++中有predefined计数? [英] How to initialize an array of vector<int> in C++ with predefined counts?

查看:203
本文介绍了如何初始化矢量&lt阵列; INT>在C ++中有predefined计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,我在STL使用C是新++。如何可以初始化每个指向5 INT元素的向量10矢量指针的阵列

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.

我的code片断如下:

My code snippet is as follows:

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

感谢

推荐答案

这将创建一个包含矢量10 矢量&lt; INT&GT; ,那些具有5个元素中的每一个:

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

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

请注意,如果外容器的大小是固定的,你的可能的要使用的std ::阵列来代替。注意初始化是更复杂的:

Note that if the size of the outer container is fixed, you might want to use an std::array instead. Note the initialization is more verbose:

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

还要注意的数组的内容是数组的一部分。它的大小,由的sizeof 给出比矢量版本较大,而且没有O(1)移动或交换操作可用。一个的std ::阵列是类似于一个固定的大小,自动存储阵列平原

Also note that the contents of array are part of the array. It's size, as given by sizeof, is larger than the vector version, and there is no O(1) move or swap operation available. An std::array is akin to a fixed size, automatic storage plain array.

还要注意的是,由于@克里斯提出的意见,你可以选择设置数组元素的之后的默认初始化,例如与的std ::填写,如果他们都具有相同的值:

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

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

等。

这篇关于如何初始化矢量&lt阵列; INT&GT;在C ++中有predefined计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆