2016-12-14 90 views
1

我自学自己从书中编程。目前的任务是我必须通过一个不返回任何内容的函数(我假设的一个void函数)来将一个带有两个下标的数组放在一起,并递归地打印每个元素。将一个数组传递给void函数,并递归地打印元素

#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接受一个数组,起始标和结束下标作为参数,返回任何内容并打印阵列。当起始下标等于结尾下标时,该函数应停止处理并返回。

+0

您也可以使用模板来推导出数组边界。 std :: array和c样式数组是可能的。也许比你的任务更先进一些,但更安全。 –

回答

3

更改签名:

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

这是编译器想要的东西! :)

+0

哦哇,工作。非常感谢你。对不起,如果它看起来像一个愚蠢的问题。当计时器让我看到时,我会将其标记为正确。 – Greg

+0

这有效,但你定义的数组只有9个值,所以它打印出第10个元素 – Steve

+0

这个值为0,这个值并不重要,我认为。在数组初始化为undefined的元素为0时,我只是匆匆地把一些数字放在那里,这样我就不会一次又一次地看到0。 – Greg

4

我认为你用C风格的“阵列”纠结了std::array。如果你改变theSource的定义

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

那么无论最后两种形式就可以了(只要你修复常量性,该编译器会抱怨),因为theArray的类型是const int的数组,而可以传递给一个正在寻找const int*的函数。

当某人使用数组作为递归练习时,几乎可以肯定他们在寻找什么。

当然,对于真实 C++,​​是比较合适的,并且应该被传递到期望const std::array<int, 10>&作为第一个参数的函数。

template<typename T, size_t S> 
std::ostream& operator<<(std::ostream& stream, const std::array<T,S>& ary) { 
    for(const auto e& : ary){ 
    stream << e << " "; 
    } 
    return stream; 
} 

此模板将与任何std::array其元素可以工作:

+0

谢谢。这是宝贵的建议,我会加入。我知道const使它保持不变,这在将数组传递给函数时非常有用。我在这上面花了很多时间是一种遗憾,因为这本书并没有给我一个很好的答案。 – Greg

0

当你这样做递归的事情数组作为一项学术活动,还可以方便地通过重载<<运营商通过std::arraycout<<'d至cout

cout << theSource << endl;