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) 我是C++的新手,我对此感到困惑:
vector<int> v = { 1,2 };
const int &r1 = v[0];
//r1 = v[1]; // compiler will show error.
Run Code Online (Sandbox Code Playgroud)
我知道r1无法重新分配引用const .但请看下面的代码:
for (const int &r2 : v) cout << r2;
Run Code Online (Sandbox Code Playgroud)
为什么不会出错?参考const r2分配了两次,对吧?