Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QList removing via iterator problem



  • Hi all,
    I've got a QList of objects named "Role", and I want to remove some of them while iterating the list. The first piece of code I wrote was:

    @
    QList<Role>::iterator roleIterator;
    for( roleIterator = roles.begin(); roleIterator != roles.end(); roleIterator++ ){
    const Role& currentRole = *roleIterator;

    if( ! currentRole.rootLevelRole() ){
        roleIterator = roles.erase( roleIterator );
    }
    

    }
    @

    but it was not working, that is it what not removing all the items. I noted that it was skipping the next-to-last-erased item, so I changed the code into

    @
    QList<Role>::iterator roleIterator;
    for( roleIterator = roles.begin(); roleIterator != roles.end(); roleIterator++ ){
    const Role& currentRole = *roleIterator;

    if( ! currentRole.rootLevelRole() ){
      roles.removeOne( currentRole );
    }
    

    }
    @

    that worked. Now I'm confused about the usage of "erase":http://qt-project.org/doc/qt-4.8/qlist.html#erase : am I not supposed to re-assign the iterator once it has been erased?



  • Have a look at "this thread":https://qt-project.org/forums/viewthread/13816/.



  • Also you can read "this article":https://qt-project.org/wiki/QtIterators



  • Sorry, not sure to get it right, but the problem is the roleIterator++ which increments the iterator that has already advanced by the erase method call. Is it right? Therefore this works:

    @
    QList<Role>::iterator roleIterator = roles.begin();
    while( roleIterator != roles.end() ){
    const Role& currentRole = *roleIterator;

        if( ! currentRole.rootLevelRole() ){
            roleIterator = roles.erase( roleIterator );
        }
         else
            roleIterator++;
      }
    

    @

    Am I right?



  • Correct.



  • Hii friends...

    I am facing problem while deleting item from QList.
    is it any difference while deleting item from QList of pointer type elements and deleting item from QList of elements(non pointer)????

    QList<Myclass*> MyList; ////////////this is list having 3 items

    //trying to delete item having name "abc"



  • the difference is that in order to avoid memory leaks you need to delete pointers and only need to remove the objects allocated on the stack.



  • If I'm not mistaken, the QList takes ownership of the inserted objects, so when deleting a "pointer" from the list, it will automatic delete the allocated data (if no other references are present).
    Greetz


Log in to reply