为什么当数组作为调用方函数中的参数传递时,不能在被调用函数中使用 foreach 循环打印数组的值

Why values of array cannot be printed using foreach loop in called function when array is passed as argument in caller function?

本文关键字:函数 调用 数组 不能 打印 循环 foreach 方函数 参数传递 为什么      更新时间:2023-10-16

我正在尝试使用 foreach 循环在调用函数中打印数组的值,但遇到编译错误。在 Linux 平台中使用 c++11 编译器并使用 VIM 编辑器。

尝试使用 C 样式 for 循环并且当大小从调用函数传递时,它起作用了

#include <iostream>
using namespace std;
void call(int [], int);
int main()
{
    int arr[] = {1,2,3,4,5};
    int size = sizeof(arr)/sizeof(arr[0]);
    call(arr,size);
}
void call(int a[],int size)
{    
    for(int i =0 ; i<size; i++)
        cout << a[i];
}

以下代码中使用的 for-each 循环,编译失败。

#include <iostream>
using namespace std;
void call(int []);
int main()
{
    int arr[] = {1,2,3,4,5};
    call(arr);
}
void call(int a[])
{
    for ( int x : a ) 
        cout << x << endl;
}

对于 C++11 中的每个循环都希望知道要迭代的数组的大小?如果是这样,它将如何帮助传统的 for 循环。还是我在这里编码的错误?

我期待着你的帮助。提前谢谢。

因为int a[]作为函数参数不是数组,所以它与写int *a相同。

您可以通过引用传递数组以使其工作:

template <size_t N> void call(int (&a)[N])

工作示例:https://ideone.com/ZlEMHC

template <size_t N> void call(int (&a)[N])
{
    for ( int x : a ) 
        cout << x << endl;
}
int main()
{
    int arr[] = {1,2,3,4,5};
    call(arr);
}