对我来说,这不会产生预期的结果:
int main() {
int i[12] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
for (auto v : i)
std::cout << v << std::endl;
for (auto v : i)
v = v+1;
for (auto v : i)
std::cout << v << std::endl;
return 0;
}
第二个for
循环似乎没有任何作用。基于范围的for
循环是只读的,还是我缺少某些内容?
答案 0 :(得分:3)
在第二个循环auto v : i
中,v
是每个i
的副本。
要更改i
的值,您需要一个reference:
int main() {
int i[12] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
for (auto v : i)
std::cout << v << std::endl;
for (auto& v : i) // Add "&" here. Now each v is a reference of i.
v = v + 1;
for (auto v : i)
std::cout << v << std::endl;
return 0;
}