有没有一种方法可以指定嵌套的STL向量在C++中的尺寸?

8
我知道向量可以按预定义的大小构建。
vector<int> foo(4);

但是有没有一种方法可以指定嵌套向量的尺寸呢?
vector< vector<int> > bar(4);

假设我想要一个大小为4的向量,其中包含大小为4的向量...就像一个4x4的整数多维数组?

2个回答

25

构造函数的第二个参数是初始化的值。现在你得到了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 ^

如果我想使用另一对<int,int>而不是int,该怎么办? 有没有一种方法可以将所有的pair初始化为包含0,0? - zebraman
@zebra:Pairs会自动将int初始化为0。但为了完整起见,我还是修改了我的帖子。 - GManNickG

1

除了使用 std::vector,您还可以使用 boost::multi_array。来自文档

#include "boost/multi_array.hpp"
#include <cassert>

int 
main () {
  // Create a 3D array that is 3 x 4 x 2
  typedef boost::multi_array<double, 3> array_type;
  typedef array_type::index index;
  array_type A(boost::extents[3][4][2]);

  // Assign values to the elements
  int values = 0;
  for(index i = 0; i != 3; ++i) 
    for(index j = 0; j != 4; ++j)
      for(index k = 0; k != 2; ++k)
        A[i][j][k] = values++;

  // Verify values
  int verify = 0;
  for(index i = 0; i != 3; ++i) 
    for(index j = 0; j != 4; ++j)
      for(index k = 0; k != 2; ++k)
        assert(A[i][j][k] == verify++);

  return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接