固定大小的常量数组的常量数组作为C++中方法的参数
const array of fixed size const array as argument of a method in C++
继我关于将数组作为常量参数传递的问题之后,我正试图弄清楚如何编写一个方法,其中参数是固定大小的常量数组的常量数组。唯一可写的内容就是这些数组的内容。
我在想这样的事情:
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
}
这个解决方案中唯一的问题是我们不知道第一个维度。有人能解决这个问题吗?
提前感谢
Kevin
[编辑]
我不想使用std::vector或这样的动态分配数组。
如果在编译时两个维度都已知,那么您可以使用二维数组(换句话说,数组数组),而不是指向数组的指针数组:
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
来管理分配的内存和跟踪大小。
引用阻止第4行(inTab = 0;
),因为您已将inTab
作为引用。const阻止第5行(inTab[0] = 0;
),因为inTab
指针是const。
相关文章:
- C++常量数组的编译时间较长
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 使用双指针传递 2D 常量数组
- 检查输入 std::array 指针数据是否等于某个常量数组
- 如何在可执行文件中存储常量数组?
- 常量数组如何在每个元素中只能包含字符,而 char* 数组能够指向每个元素中的字符串?
- LLVM 无法将数组类型强制转换为常量数组
- 如何在C++中的单行中返回常量数组中的值
- C++ 具有常量数组和initializer_list的重载构造函数
- 在可变参数构造函数中初始化常量数组
- 非常量数组
- C/C++ 中的常量数组和静态常量数组有什么区别
- C++全局常量数组:是否保证合并(优化)到一个副本中
- 在常量数组上使用指针遍历
- 具有函数指针常量数组的 C++ 模板化静态类
- 字符常量数组为空,即使已为其赋值 [C++]
- 指向常量数组的指针
- 函数指针的常量数组令人困惑
- 在 c++ 中初始化静态常量数组
- 常量数组类成员初始化