std::vector<MyClass> vec;
for (auto &x : vec)
{
// x is a reference to an item of vec
// We can change vec's items by changing x
}
Run Code Online (Sandbox Code Playgroud)
要么
for (auto x : vec)
{
// Value of x is copied from an item of vec
// We can not change vec's items by changing x
}
Run Code Online (Sandbox Code Playgroud)
好.
当我们不需要更改vec项目时,IMO,示例建议使用第二个版本(按值).为什么他们不提出const引用的内容(至少我没有找到任何直接的建议):
for (auto const &x : vec) // <-- see …Run Code Online (Sandbox Code Playgroud)