我知道,我们可以以这种方式遍历作为参数传递的数组:
//NO ERROR
void fun(int *a, int n){
for(int i=0; i<n; i++)
cout<<a[i];
}
但是,有什么方法可以使用像这样的函数中的for-each循环遍历数组? //ERROR
void fun(int *a, int n){
for(auto x:a)
cout<<x;
}
最佳答案
指针不是数组。如果将指向数组第一个元素的指针传递给函数,则它不再是数组,而是指针。
您可以在pass the array by reference时使用基于范围的循环:
#include <iostream>
template <size_t N>
void foo(int (&x)[N]) {
for (int i : x) std::cout << i << " ";
}
int main() {
int x[] = {1,2,3};
foo(x);
}
输出:1 2 3
这是可行的,因为基于范围的循环使用std::begin(x)
和std::end(x)
将迭代器获取到数组的开头和结尾。指针没有开始或结束。
关于c++ - 我们可以使用for-each循环遍历传递给函数的数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66491831/