QList <int> replace value

1.8k views Asked by At

I have QList of int.

eg: [10,10];

Then I want to reduce the value by 1.

I tried:

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

But qDebug of valList shows their values remain as 10. What did I do wrong?

2

There are 2 answers

0
Alexander V On BEST ANSWER

I would try this with C++ 11 and later:

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

P.S. Have not tried to compile.

1
Dmitry On

You cannot use foreach for changing the values within the container you are iterating over as the official documentation says:

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.