Search code examples
c++qtiteratorqtcoreqstringlist

Remove item from QStringlist using iterator


I am trying to iterate through a QStringList, printing the string, and then removing it from the list. I can't seem to find a QStringList method that works! For example:

for ( QStringList::Iterator it = commandList.begin(); it != commandList.end(); ++it ) {
    out << "Processed command: " << *it << endl;
    *it.erase();
}

gives the compiler error: 'QList::Iterator' has no member named 'erase'

  1. How would I remove the items currently pointed to by the iterator?
  2. Is it safe to remove it IN the loop? (Since the ++it may fail if I remove an item midway through the list)

Solution

  • Another solution is the use of QMutableStringListIterator, it can be used as any other iterator, but it has the method "remove" that you are looking for.

     QMutableStringListIterator i(list); // pass list as argument
     while (i.hasNext()) { 
         i.remove();                      // delete current item
     }