Qt: is removing QList elements while iterating using foreach macro possible?

前端 未结 3 397
有刺的猬
有刺的猬 2020-12-30 20:26

I\'m new to Qt and trying to learn the idioms.

The foreach documentation says:

Qt automatically takes a copy of the container when it enters a

相关标签:
3条回答
  • 2020-12-30 21:10

    If the test function is reentrant, you could also use QtConcurrent to remove the "bad" elements:

    #include <QtCore/QtConcurrentFilter>
    ...
    QtConcurrent::blockingFilter(fooList, bad);
    

    Or the STL variant:

    #include <algorithm>
    ...
    fooList.erase(std::remove_if(fooList.begin(), fooList.end(), bad), 
                  fooList.end());
    
    0 讨论(0)
  • 2020-12-30 21:14

    You should better use iterators for that:

    // Remove all odd numbers from a QList<int> 
    QMutableListIterator<int> i(list);
    while (i.hasNext()) {
        if (i.next() % 2 != 0)
            i.remove();
    }
    
    0 讨论(0)
  • 2020-12-30 21:27

    If you don't want a copy at all, use iterators. Something like:

    QList<yourtype>::iterator it = fooList.begin();
    while (it != fooList.end()) {
      if (bad(*it))
        it = fooList.erase(it);
      else
        ++it;
    }
    

    (And make sure you really want to use a QList instead of a QLinkedList.)

    foreach is really nice when you want to traverse a collection for inspection, but as you have found, it's hard to reason about when you want to change the structure of the underlying collection (not the values stored in there). So I avoid it in that case, simply because I can't figure out if it is safe or how much copying overhead happens.

    0 讨论(0)
提交回复
热议问题