QList <int> 替换值

QList <int> replace value

我有一个整型的QList。

eg: [10,10];

那我要减1.

我试过了:

foreach (int val, valList) {
    val-= 1;
}

但是 valList 的 qDebug 显示它们的值仍然是 10。我做错了什么?

您不能使用 foreach 来更改您正在迭代的容器中的值,正如 the official 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 do not modify the container, the copy still takes place, but thanks to implicit sharing copying a container is very fast.)

Since foreach creates a copy of the container, using a non-const reference for the variable does not allow you to modify the original container. It only affects the copy, which is probably not what you want.

An alternative to Qt's foreach loop is the range-based for that is part of C++ 11 and newer. However, keep in mind that the range-based for might force a Qt container to detach, whereas foreach would not. But using foreach always copies the container, which is usually not cheap for STL containers. If in doubt, prefer foreach for Qt containers, and range based for for STL ones.

我会尝试使用 C++ 11 及更高版本:

void changeIntVals(QList<int>& valList)
{
   for(auto& val: valList)
   {
      val -= 1;
   }
}

P.S。没试过编译。