将数组传递到空隙函数,然后递归打印元素
Pass an array to a void function, and recursively print the elements
我是自学从书中编写的。手头的任务是,我必须通过一个返回什么都没有返回的函数(我假设的无效函数)放置一个带有两个下标的数组,然后递归打印每个元素。
#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>&
作为其第一个参数的函数。
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 使用递归的数组的最小值.这是怎么回事
- 递归列出所有目录中的C++与Python与Ruby的性能
- 递归计数给定目录的文件和所有目录
- 如何在BST的这个简单递归实现中消除警告
- C++:正在检查LinkedList中的回文-递归方法-错误
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 递归无序映射
- TSP递归解的迭代形式
- 如何在Elixir中调用递归函数并行
- 返回递归调用和仅递归调用的区别
- 数组元素打印的递归方法
- 使用递归时获取变量的奇怪值
- 如何在C++中递归地按相反顺序打印集合
- 到连接组件算法的问题(递归)
- 为什么我的递归函数按降序打印,然后按升序打印?
- 不明白为什么这个简单的递归开始工作然后崩溃
- 将数组传递到空隙函数,然后递归打印元素
- 将一个数字的一个数字与其当前位置相乘,然后使用递归将其和其他数字相加