问题描述
我知道向量可以构造成预定义的大小。
I know vectors can be constructed to a predefined size
vector<int> foo(4);
但是有办法指定嵌套向量的维数吗?
But is there a way to specify the dimensions of nested vectors?
vector< vector<int> > bar(4);
假设我想要一个大小为4的向量,包含大小为4的向量...就像一个4x4的多维array of ints?
Lets say I wanted a vector of size 4 containing vector's of size 4... like a 4x4 multidimensional array of ints?
推荐答案
是要初始化的值。现在你得到4个默认构造的向量。为了澄清一个更简单的1D示例:
The second argument to that constructor is the value to initialize with. Right now you're getting 4 default-constructed vectors. To clarify with a simpler 1D example:
// 4 ints initialized to 0
vector<int> v1(4);
// *exactly* the same as above, this is what the compiler ends up generating
vector<int> v2(4, 0);
// 4 ints initialized to 10
vector<int> v3(4, 10);
所以你想要:
vector< vector<int> > bar(4, vector<int>(4));
// this many ^ of these ^
这将创建一个int类型的向量向量,初始化为包含4个向量,这些向量被初始化为包含4个int,初始化为0.(如果需要,您可以为int指定默认值。)
This creates a vector of vectors of ints, initialized to contain 4 vectors that are initialized to contain 4 ints, initialized to 0. (You could specify a default value for the int to, if desired.)
- 全,但不要太硬。 :)
A mouth-full, but not too hard. :)
对于:
typedef std::pair<int, int> pair_type; // be liberal in your use of typedef
typedef std::vector<pair_type> inner_vec;
typedef std::vector<inner_vec> outer_vec;
outer_vec v(5, inner_vec(5, pair_type(1, 1)); // 5x5 of pairs equal to (1, 1)
// this many ^ of these ^
//this many ^ of these ^
这篇关于是否有一种方法来指定嵌套STL向量C ++的维度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!