我知道向量可以构造为预定义的大小
vector<int> foo(4);
但是有没有办法指定嵌套向量的维度呢?
vector< vector<int> > bar(4);
假设我想要一个大小为 4 的向量,其中包含大小为 4 的向量...就像一个 4x4 多维整数数组?
第二个参数那个构造函数 http://en.cppreference.com/w/cpp/container/vector/vector是要初始化的值。现在您将获得 4 个默认构造的向量。用一个更简单的一维示例来阐明:
// 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 ^
这将创建一个由整数向量组成的向量,初始化为包含 4 个向量,这些向量初始化为包含 4 个整数,初始化为 0。(如果需要,您可以为 int 指定默认值。)
满嘴都是,但又不太硬。 :)
对于一对:
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 ^
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)