为什么foreach使用const引用进行迭代? [英] Why is foreach iterating with a const reference?

查看:219
本文介绍了为什么foreach使用const引用进行迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试做以下操作:

  QList< QString>一个; 
foreach(QString& s,a)
{
s + =s;





$ b看起来应该是合法的,但我最终抱怨说它不能从'const QString'转换为'QString&'

为什么Qt foreach迭代一个const引用?

解决方案

正如
$ b


Qt自动获取一个容器的副本,当它进入一个foreach循环。如果您在迭代时修改容器,则不会影响循环。 (如果你不修改容器,复制仍然会发生,但是由于隐式共享复制容器是非常快的。)同样,声明变量是一个非const引用,以修改当前项目这个列表也是行不通的。

它是一个副本,因为你可能想从列表中删除一个项目或者添加项目例如循环。缺点是你的用例是行不通的。 (QList< QString> :: iterator i = a.begin())将不得不遍历整个列表:

  ; i!= a.end(); ++ i){
(* i)+ =s;
}

再多输入一点,但不要太多。

I try to do the following:

QList<QString> a;
foreach(QString& s, a)
{
    s += "s";
}

Which looks like it should be legitimate but I end up with an error complaining that it cannot convert from 'const QString' to 'QString &'.

Why is the Qt foreach iterating with a const reference?

解决方案

As explained on the 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.

It makes a copy because you might want to remove an item from the list or add items while you are looping for example. The downside is that your use case will not work. You will have to iterate over the list instead:

for (QList<QString>::iterator i = a.begin(); i != a.end(); ++i) { 
  (*i) += "s";
} 

A little more typing, but not too much more.

这篇关于为什么foreach使用const引用进行迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆