我正在尝试使用foreach循环在调用的函数中打印数组的值,但遇到编译错误。在Linux平台上使用c ++ 11编译器并使用VIM编辑器。
当从调用函数传递大小时,尝试使用C样式进行循环并成功
#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];
}
Run Code Online (Sandbox Code Playgroud)
以下代码中使用的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;
}
Run Code Online (Sandbox Code Playgroud)
C ++ 11中的for-each循环希望知道要迭代的数组的大小?如果是这样,那么相对于传统的for循环它将如何有所帮助。还是我在这里编码的错误?
期待您的帮助。提前致谢。
Because int a[] as function parameter is not an array, it is the same as writing int *a.
You can pass the array by reference to make it work:
template <size_t N> void call(int (&a)[N])
Run Code Online (Sandbox Code Playgroud)
working example: 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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |