【发布时间】:2021-10-10 07:33:43
【问题描述】:
我是 C++ 新手,我想创建一个函数,该函数将某个大小的空数组作为默认值。基本上,数组应该像迭代函数调用的存储一样,函数最后会在该数组中返回一些值。我需要一个空数组,因为我的函数将是递归的。
我尝试了以下代码,但没有成功,问题在于int& M[a][b],我不知道定义空数组的正确方法是什么。
#include<iostream>
void foo(const int& a, const int& b, int (&M)[a][b]){
std::cout<<a<<'\n';
}
int main(){
int M[2][3];
foo(2,3,M);
}
这是错误信息
error: cannot bind rvalue '(int)((int (*)[3])(& M))' to 'int&'
【问题讨论】:
-
“空数组”是什么意思?数组的大小是固定的。
-
固定(静态大小)数组的大小必须在编译时知道(例如
constexpr)。在 c++ 中,您可以使用std::array(std::vector,以防编译时大小未知)。 -
void foo(const int& a, const int&b, std::vector<std::vector<int>>& M) -
对于它的价值,您的问题既不包含空数组也不包含默认参数;-)。所以我很困惑:您的问题主体是否仍然不完整(即不包含实际问题的示例),还是您在标题中写了一些不能准确描述您的问题的内容?
-
一般来说,提供“空”默认参数的一个好方法是使用指针参数(而不是引用)并使用
nullptr作为默认值。
标签: c++ c++11 multidimensional-array