我已经声明了一个恒定大小的数组,并尝试使用 for 每个循环获取输入,但是 它无法接受数组总元素的输入。
int main(){
int a[5];
for(int x: a){
cin>>x;
}
}
不允许在每个循环中使用此方法来获取数组元素的输入。 解释一下上面的疑惑。
您正在通过复制进行迭代,如果您想填充数组,则需要使用指针或引用。
因此:
int main(){
int a[5];
for(int x: a){ // x is a copy of the current element
cin>>x;
}
}
对此:
int main(){
int a[5];
for(int& x: a){ // x is a reference of the current element
cin>>x;
}
}