将数组传递到空隙函数,然后递归打印元素

Pass an array to a void function, and recursively print the elements

本文关键字:然后 递归 打印 元素 函数 数组      更新时间:2023-10-16

我是自学从书中编写的。手头的任务是,我必须通过一个返回什么都没有返回的函数(我假设的无效函数)放置一个带有两个下标的数组,然后递归打印每个元素。

#include <iostream>
#include <array>
#include <iomanip>
#include <string>
#include <cstddef>
using namespace std;
void printArray (int source, int a, int b){
    if (a < b){
        cout << source[a] << " ";
        printArray(source, a + 1, b);
        }
}
int main (){
    const array<int, 10> theSource = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int al = 0;
    int bl = theSource.size();
    printArray(theSource, al, bl);
}

当我尝试这样做时,我会遇到两个错误。

11|error: invalid types 'int[int]' for array subscript|
22|error: cannot convert 'const std::array<int, 10u>' to 'int' for argument '1' to 'void printArray(int, int, int)'|

所以我尝试将空白更改为...

void printArray (int source[], int a, int b)

以及...

void printArray (int *source, int a, int b){

,但仍然会出现错误...

22|error: cannot convert 'const std::array<int, 10u>' to 'int' for argument '1' to 'void printArray(int, int, int)'|

有其他方法可以通过函数放置数组?

任务是...

(打印一个数组)编写一个递归函数printarray,该函数将数组,启动子标记和一个结尾标作为参数作为参数,没有返回并打印数组。当起始下标等于结束下标。

时,该功能应停止处理并返回。

将签名更改为:

void printArray (const array<int, 10> &source, int a, int b)

这是编译器想要的!:)

我认为您正在用C风格的"数组"纠结std::array。如果将theSource的定义更改为

const int theSource[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

然后,最后两种表格中的任何一个都将起作用(只要您修复了编译器会抱怨的constness),因为theArray具有const int的类型数组,并且可以传递给正在寻找const int*的函数。/p>

当有人将阵列用作递归中的练习时,几乎可以肯定是他们想要的。

当然,对于 real C ,std::array<int, 10> theArray更合适,应传递给期望const std::array<int, 10>&作为其第一个参数的函数。