【问题标题】:const array of fixed size const array as argument of a method in C++固定大小的 const 数组 const 数组作为 C++ 中方法的参数
【发布时间】:2012-07-22 14:20:36
【问题描述】:

在我关于passing array as const argument 的问题之后,我试图弄清楚如何编写一个方法,其中参数是固定大小的 const 数组的 const 数组。唯一可写的就是这些数组的内容。

我正在考虑这样的事情:

template <size_t N>
void myMethod(int* const (&inTab)[N])
{
    inTab = 0;       // this won't compile
    inTab[0] = 0;    // this won't compile
    inTab[0][0] = 0; // this will compile
}

这个解决方案的唯一问题是我们不知道第一个维度。 有人对此有解决方案吗?

提前致谢,

凯文

[编辑]

我不想使用 std::vector 或这种动态分配的数组。

【问题讨论】:

  • The only writable thing would be the content of these arrays.the argument is a const array 不能很好地结合在一起
  • 我不确定我是否理解,但是传递一个数组数组是这样完成的:template &lt;size_t N, size_t M&gt; void myMethod(int (&amp;inTab)[N][M]).
  • @SingerOfTheFall:这很有意义:它是一个指向可写数组的常量数组。
  • 不过,你还是得给这个方法传递一个连续的数据块吧?
  • @MikeSeymour,嗯,我认为where the argument is a const array of fixed size const array 的意思是“常量数组的常量数组”...

标签: c++ multidimensional-array constants argument-passing


【解决方案1】:

如果在编译时两个维度都是已知的,那么您可以使用二维数组(换句话说,数组数组)而不是指向数组的指针数组:

template <size_t N, size_t M>
void myMethod(int (&inTab)[N][M])
{
    inTab = 0;       // this won't compile
    inTab[0] = 0;    // this won't compile
    inTab[0][0] = 0; // this will compile
}

int stuff[3][42];
myMethod(stuff); // infers N=3, M=42

如果任一维度在运行时未知,则可能需要动态分配数组。在这种情况下,请考虑使用std::vector 来管理分配的内存并跟踪大小。

【讨论】:

    【解决方案2】:

    引用阻止了第 4 行 (inTab = 0;),因为您已将 inTab 设为引用。 const 阻止了第 5 行 (inTab[0] = 0;),因为 inTab 指针是 const。

    【讨论】:

      猜你喜欢
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多