【问题标题】:C++ Attempting to define 2D array using function argumentsC ++尝试使用函数参数定义二维数组
【发布时间】:2019-05-19 02:59:20
【问题描述】:

我正在寻找定义一个二维字符数组,其中我传递给保存数组的函数的参数将用于确定数组每个维度的大小。

int func(const int x, const int y) {

    char maze[x][y] = { 0 };
    return 0; 
}

当在函数内部将 x 和 y 定义为常量整数时,数组定义得很好。当 x 和 y 是函数的参数时,程序将无法编译。为什么会这样,我该如何解决?

【问题讨论】:

  • 这在标准 c++ 中是不合法的。 xy 都需要是编译时常量而不是函数参数。
  • 由于大小不是编译时常量,所以需要一个动态数组。换句话说,std::vector
  • 使用std::vector<char> maze(x * y);。然后,不要像 maze[pos_y][pos_x] 那样使用它:maze[pos_x + pos_y * x]
  • 你可以使用 xy 的模板,但我认为这不是你要找的

标签: c++ arrays arguments 2d constants


【解决方案1】:

当在函数内部将 x & y 定义为常量整数时,数组定义得很好

因为你的数组的大小是由你的编译器定义和知道的,在编译时

知道

当 x 和 y 是函数的参数时,程序将无法编译。

如果您希望仅在 调用 函数时定义数组,则要求程序在 运行时 期间执行此操作 .正如 Dmytro Dadyka 所回答的,您必须使用 动态内存分配 并管理自己的内存释放(delete[] maze; // delete)

这是使用模板动态定义二维数组的替代方法!请注意,它总是在编译时完成。

template<int X, int Y>
int f()
{
    char c[X][Y];

    for(int x=0; x < X; ++x)
    {
        for(int y=0; y < Y; ++y)
        {
            c[x][y] = '1';
        }


    }
    // write your algorithm now!....
    c[2][2] = 'a';

    for(int x=0; x < X; ++x)
    {
        for(int y=0; y < Y; ++y)
        {
           std::cout << c[x][y] << " ";
        }
        std::cout << std::endl;
    }
    return 0;
}

    int main()
    {
      f<5,5>();
      f<7,4>();
      return 0;
    }

【讨论】:

    【解决方案2】:

    您需要使用动态内存分配。可变长度数组不是 C++ 标准的一部分。然而,可变长度数组可用作 GCC 的扩展。虽然您可以使用 STL 或实现您的类,但不要忘记 new[] 和二维数组的一维表示:

    char* maze = new char[x*y]; // create
    maze[i + j * x]; // access
    delete[] maze; // delete
    

    它很紧凑,在大多数情况下速度很快。

    【讨论】:

      【解决方案3】:

      您可以像这样围绕一维数组制作一个包装器:

      class Maze {
          friend class Row;
      public:
          /* This helper class represents a single row of the maze */
          class Row {
              friend class Maze;
              Maze& owner;
              std::size_t row;
              Row(Maze& owner_, std::size_t row_) : owner(owner_), row(row_) {}
              /* this operator resolves 2nd pair of brackets */
          public:
              inline char& operator[](std::size_t col) { return owner.data[col + row*owner.cols]; }
          };
          Maze(std::size_t rows_, std::size_t cols_)
            : data(rows_ * cols_, 0)
            , cols(cols_)
          {}
          /* this operator resolves 1st pair of brackets */
          inline Row operator[](std::size_t index) { return Row(*this, index); }
      private:
          std::vector<char> data;
          std::size_t cols;
      };
      

      ...

      Maze m(5, 10);
      m[2][3] = 1;
      

      【讨论】:

      • operator[] 可以返回指向行首的指针 (return data.data() + index * cols;),因此您不需要内部类。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      • 2018-03-15
      相关资源
      最近更新 更多