【问题标题】:Populating a multidimensional vector during runtime在运行时填充多维向量
【发布时间】:2014-01-31 00:20:09
【问题描述】:

显然这不起作用,所以代码是错误的,但我该如何解决呢? 就我所知,这整件事可能是错误的,哈哈,但我正在尝试创建一个在运行时创建自身的多维向量。我收到一个错误:vector subscript out of range。

#include <iostream>
#include <vector>

int main(){
   int row = 0, col = 0;
   std::cout << "Size of Row: "; std::cin >> row; 
   std::cout << "Size of Column: "; std::cin >> col;

   std::vector<std::vector<int>> td;
   td.resize(row * col);

   for (int i = 0; i <= row; i++){
      for (int j = 0; j <= col; j++){
        td[i][j];
      }
   }
}

【问题讨论】:

    标签: c++ vector multidimensional-array


    【解决方案1】:

    当你使用

    td.resize(row * col);
    

    td 的第一个维度将为 row*col,但其第二个维度仍为空。这就是你得到错误的原因。

    你应该使用

    td.resize(row); // set first dimension
    for (int i=0; i<row; i++) // set each second dimenstion
        td[i].resize(col);
    

    或者干脆

    vector<vector<int>> td(row, vector<int>(col)); // has rows, each of them has cols
    

    【讨论】:

      【解决方案2】:

      您需要为向量的向量分配适当的内存量。您可以使用以下代码显式设置空行和空列的数量,而不是调整其大小。

      std::vector< std::vector<int> > td(row+1, std::vector<int>(col+1)); 
      //+1 is needed because the loop you created is <=
      

      否则,您可以调整循环并执行以下操作:

      std::vector< std::vector<int> > td(row, std::vector<int>(col));
      
      for (int i = 0; i < row; i++){
        for (int j = 0; j < col; j++){
          td[i][j];
        }
      }
      

      【讨论】:

        【解决方案3】:

        td 指的是外部向量,因此您的调整大小会产生一个由 row'col 空向量组成的向量。您需要将其调整为仅行,然后您的 for i 循环可以在内部说 td[i].resize(col) 以使其成为二维。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-10-23
          • 1970-01-01
          • 2023-01-23
          • 1970-01-01
          • 1970-01-01
          • 2011-01-11
          相关资源
          最近更新 更多