Results 1 to 5 of 5

Thread: Weird behavior in QList.erase

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Join Date
    Dec 2009
    Location
    New Orleans, Louisiana
    Posts
    791
    Thanks
    13
    Thanked 153 Times in 150 Posts
    Qt products
    Qt5
    Platforms
    MacOS X

    Default Re: Weird behavior in QList.erase

    Does the following accomplish what you want?

    Qt Code:
    1. vectorOutput = vectorFirst;
    2.  
    3. QVectorIterator<Data*> itOutput(vectorOutput);
    4. QVectorIterator<Data*> itSecond(vectorSecond);
    5.  
    6. while (itOutput.hasNext())
    7. {
    8. Data *d1 = itOutput.next();
    9. vectorSecond.toFront();
    10. while (itSecond.hasNext())
    11. {
    12. Data *d2 = itSecond.next();
    13. if (d1->x == d2->x && d1->y == d2->y)
    14. {
    15. vectorDeleted.push_back(d1);
    16. vectorOutput.removeOne(d1);
    17. }
    18. }
    19. }
    To copy to clipboard, switch view to plain text mode 

  2. #2
    Join Date
    Jan 2008
    Location
    Alameda, CA, USA
    Posts
    5,328
    Thanks
    317
    Thanked 871 Times in 858 Posts
    Qt products
    Qt5
    Platforms
    Windows

    Default Re: Weird behavior in QList.erase

    erase() returns the iterator pointing to the next element.
    But the trick to this is you have to continuously evaluate container.end() as part of the for() loop termination condition. You can't assign it to a variable prior to entering the for() loop, because the value it holds will become invalid as soon as the container content changes (either through insertion or erasure). In other words, this will not work:

    Qt Code:
    1. QVector<Data *>::iterator it;
    2. QVector<Data *>::iterator eIt = container.end();
    3. for (it = container.begin(); it != eIt; /* no ++ here */) {
    4. if (condition) {
    5. it = container.erase(it);
    6. }else {
    7. // only increment if no delete happened
    8. ++it;
    9. }
    10. }
    To copy to clipboard, switch view to plain text mode 

Similar Threads

  1. Weird setStyleSheet() behavior in Qt 5.3
    By Carlsberg in forum Qt Programming
    Replies: 0
    Last Post: 10th June 2014, 16:00
  2. QWebview weird behavior on some pages
    By ZaQ in forum Qt Programming
    Replies: 1
    Last Post: 15th April 2011, 03:24
  3. QWebView weird behavior !!
    By gontham in forum Newbie
    Replies: 1
    Last Post: 21st October 2010, 14:00
  4. Weird removeRow behavior
    By metalinspired in forum Qt Programming
    Replies: 0
    Last Post: 30th August 2009, 12:42
  5. Weird QMenu behavior on Mac
    By munna in forum Qt Programming
    Replies: 1
    Last Post: 14th January 2009, 15:18

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Qt is a trademark of The Qt Company.