范围为语句不能使用数组函数参数构建范围表达式 [英] Range-for-statement cannot build range expression with array function parameter
本文介绍了范围为语句不能使用数组函数参数构建范围表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么无法构建范围表达式将数组作为函数参数传递并在范围为语句中使用。
感谢您的帮助
Why cannot build range expression passing an array as a function argument and using in a range-for-statement. Thanks for the help
void increment(int v[]){
// No problem
int w[10] = {9,8,7,6,5,4,3,2,1,9};
for(int& x:w){
std::cout<<"range-for-statement: "<<++x<<"\n";
}
// error: cannot build range expression with array function
// parameter 'v' since parameter with array type 'int []' is
// treated as pointer type 'int *'
for(int x:v){
std::cout<<"printing "<<x<<"\n";
}
// No problem
for (int i = 0; i < 10; i++){
int* p = &v[i];
}
}
int main()
{
int v[10] = {9,8,7,6,5,4,3,2,1,9};
increment(v);
}
推荐答案
$ c> v 是不是数组的指针 - 如错误消息所示。内置数组是奇怪的东西,它不能被复制或通过值传递,并在尴尬的时刻自然变成指针。
Despite appearances, v
is a pointer not an array - as the error message says. Built-in arrays are weird things, which can't be copied or passed by value, and silently turn into pointers at awkward moments.
没有办法知道它指向的数组的大小,所以没有办法生成一个循环来遍历它。选项包括:
There is no way to know the size of the array it points to, so no way to generate a loop to iterate over it. Options include:
- 使用适当的范围样式容器,例如
std :: array
或std :: vector
- 将数组的大小作为一个额外的参数传递, / li>
- use a proper range-style container, like
std::array
orstd::vector
- pass the size of the array as an extra argument, and interate with an old-school loop
这篇关于范围为语句不能使用数组函数参数构建范围表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文