gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:30:36 25 4
gpt4 key购买 nike

我的代码:

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;
}

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

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

最佳答案

当你写作时

for (auto vec : v) vec.clear(); //

然后 auto被推断为 std::vector<int> ,因此 vecv 元素的拷贝.您清除拷贝,但保留实际元素不变。如果你想对元素本身进行操作,你必须使用引用:

for (auto& vec : v) vec.clear();

我个人的经验法则是在使用 auto 时始终明确提及指针性、常量性和引用性。 .我认为它使用了 auto更具可读性,但这只是我的意见。请注意,在这里您别无选择,但如果您遵循规则,您可能会更容易地意识到 vec是值,不是引用。

关于c++ - 为什么 vector::clear 在 foreach 循环中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54205530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com