6
vector<vector<int>> sort_a;
vector<int> v2;
vector<int> v3;

for (int i=0; i<4; ++i) {
v2.push_back(i);

  for (int j=0; j<4; ++j) {
  v3.push_back(j);
  sort_a.push_back(v2);
  sort_a.push_back(v3);
  }

}

向量 sort_a 应该是一个 4x4 数组,而不是输出是 31x1 有很多空元素,我如何在多维向量中插入元素?

4

2 回答 2

9

不要将其视为多维向量,将其视为向量的向量。

int n = 4;
std::vector<std::vector<int>> vec(n, std::vector<int>(n));

// looping through outer vector vec
for (int i = 0; i < n; i++) {
  // looping through inner vector vec[i]
  for (int j = 0; j < n; j++) {
    (vec[i])[j] = i*n + j;
  }
}

我在括号中加入(vec[i])[j]只是为了便于理解。

编辑:

如果你想通过 填充你的向量push_back,你可以在内部循环中创建一个临时向量,填充它,然后 push_back 它到你的向量:

for (int i = 0; i < n; i++) {
  std::vector<int> temp_vec;

  for (int j = 0; j < n; j++) {
    temp_vec.push_back(j);
  }

  vec.push_back(temp_vec);
}

但是,push_back调用会导致代码变慢,因为您不仅需要一直重新分配向量,而且还必须创建一个临时的并复制它。

于 2012-12-18T15:59:58.227 回答
4

avector<vector<int>>不是多维存储的最佳实现。以下植入对我有用。

template<typename T>
class array_2d {
    std::size_t data;
    std::size_t col_max;
    std::size_t row_max;
    std::vector<T> a;
public:
    array_2d(std::size_t col, std::size_t row) 
         : data(col*row), col_max(col), row_max(row), a(data)
    {}

    T& operator()(std::size_t col, std::size_t row) {
        assert(col_max > col && row_max > row)
        return a[col_max*col + row];
    }
};

用例:

array_2d<int> a(2,2);
a(0,0) = 1;
cout << a(0,0) << endl;

此解决方案类似于此处描述的解决方案。

于 2012-12-18T16:28:31.963 回答