我尝试执行以下操作:
QList<QString> a;
foreach(QString& s, a)
{
s += "s";
}
这看起来应该是合法的,但我最终遇到了一个错误,提示它 cannot convert from 'const QString' to 'QString &'
。
为什么 Qt foreach 使用 const 引用进行迭代?
最佳答案
如 Qt Generic Containers Documentation 中所述:
Qt automatically takes a copy of the container when it enters a foreach loop. If you modify the container as you are iterating, that won't affect the loop. (If you don't modify the container, the copy still takes place, but thanks to implicit sharing copying a container is very fast.) Similarly, declaring the variable to be a non-const reference, in order to modify the current item in the list will not work either.
它制作拷贝是因为您可能想从列表中删除一个项目或在循环时添加项目。缺点是您的用例将不起作用。您将不得不遍历列表:
for (QList<QString>::iterator i = a.begin(); i != a.end(); ++i) {
(*i) += "s";
}
多打一点字,但不要太多。
关于c++ - 为什么 foreach 使用 const 引用进行迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1600928/