【问题标题】:C++ How to pass empty array as default argument in a functionC ++如何将空数组作为函数中的默认参数传递
【发布时间】: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::arraystd::vector,以防编译时大小未知)。
  • void foo(const int&amp; a, const int&amp;b, std::vector&lt;std::vector&lt;int&gt;&gt;&amp; M)
  • 对于它的价值,您的问题既不包含空数组也不包含默认参数;-)。所以我很困惑:您的问题主体是否仍然不完整(即不包含实际问题的示例),还是您在标题中写了一些不能准确描述您的问题的内容?
  • 一般来说,提供“空”默认参数的一个好方法是使用指针参数(而不是引用)并使用nullptr作为默认值。

标签: c++ c++11 multidimensional-array


【解决方案1】:

请注意,您所说的空数组实际上不是空数组。当我们写:

int arr[3]; 

这意味着arr 是一个由 3 个整数组成的数组,其元素默认初始化。所以它不是一个空数组。

以下是使用模板的工作示例,展示了如何将数组传递给函数。

版本 1:用于传递一维数组

#include <iostream>
template<std::size_t N, std::size_t M>
void foo(const int (&array1)[N], const int (&array2)[M])
{
    std::cout<<"size of passed array1 is: "<<N<<std::endl;
    std::cout<<"size of passed array1 is: "<<M<<std::endl;
}


int main()
{
    std::cout<<"Hello World"<<std::endl;
    int arr[] = {1,2,3,4};
    int arr2[] = {1,4};
    foo(arr, arr2);
    return 0;
}

版本 2:用于传递 2D 数组

#include <iostream>
template<std::size_t N, std::size_t M>
void foo(const int (&array1)[N][M])
{
    std::cout<<"width of passed array is: "<<N<<std::endl;
    std::cout<<"height of passed array2 is: "<<M<<std::endl;
}
int main()
{
    std::cout<<"Hello World"<<std::endl;
    int arr[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};
    foo(arr);
    
    //now you can pass an array whose elements are default initialized
    int arr2[5][6];
    foo(arr2);
    return 0;
}

另外,您可以使用std::vector

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 2013-08-12
    • 2011-03-29
    • 2014-08-08
    • 2017-11-08
    • 2016-05-12
    相关资源
    最近更新 更多