为什么vector :: clear在foreach循环中不起作用?

Sau*_*ahu 0 c++ foreach for-loop vector

我的代码:

vector<int> v[10];
const int x = 3;
void clearBySimpleLoop(){
    for (int i = 0; i < x; i++){
        v[i].clear();
    }
}
int main()
{
    for (int i = 0; i < x; i++){
        v[i].push_back(11+i);
        v[i].push_back(11+i+1);
        v[i].push_back(11+i+2);
    }
    for (auto vec : v) vec.clear(); //#01. Contents are not cleared. Size of the contained vectors remains same.
    clearBySimpleLoop(); //#02. Contents are cleared. Size of the contained vectors becomes zero. 
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

问题是为什么foreach循环(#01)中的代码无法清除数组中的向量,而简单的for循环(#02)成功了?

演示:https://onlinegdb.com/B1m8-2jG4

for*_*818 6

当你写作

for (auto vec : v) vec.clear(); //
Run Code Online (Sandbox Code Playgroud)

然后auto得到了解释std::vector<int>,因此vec是元素的副本v.您清除副本,但保持实际元素不变.如果你想对元素进行操作,你必须使用引用:

for (auto& vec : v) vec.clear();
Run Code Online (Sandbox Code Playgroud)

我个人的经验法则是在使用时总是明确提到指针,常量和参考auto.我认为它使得用法auto更具可读性,但这仅仅是我的观点.请注意,在这里您别无选择,但如果您遵循该规则,您可以更容易地实现vec价值,而不是参考.