对范围 for 循环感到困惑

Confused about ranged for loops

对我来说,这不会产生预期的结果:

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 循环是只读的,还是我遗漏了什么?

在你的第二个循环中,auto v : iv 是每个 i.

copy

要更改 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;
}

演示:https://ideone.com/DVQllH.