Results 1 to 9 of 9

Thread: vector & remove_if

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Join Date
    Jan 2006
    Posts
    976
    Thanks
    53
    Qt products
    Qt3
    Platforms
    Windows

    Default Re: vector & remove_if

    sorry,
    what I meant was:
    This seems work:
    Qt Code:
    1. vector<double>::iterator ivalid = validValue.end() - 1;
    2. vector<bool>::iterator imask = _indexMissedMask.end() - 1;
    3. for ( ; imask != _indexMissedMask.begin(); --imask) {
    4. if ( *imask )
    5. validValue.erase(ivalid--);
    6. }
    To copy to clipboard, switch view to plain text mode 
    This crashes:
    Qt Code:
    1. vector<double>::iterator ivalid = validValue.end() - 1;
    2. vector<bool>::iterator imask = _indexMissedMask.end() - 1;
    3. for ( ; imask != _indexMissedMask.begin(); --imask, --ivalid) {
    4. if ( *imask )
    5. validValue.erase(ivalid);
    6. }
    To copy to clipboard, switch view to plain text mode 
    Why, please?
    Regards

  2. #2
    Join Date
    Dec 2006
    Posts
    849
    Thanks
    6
    Thanked 163 Times in 151 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11

    Default Re: vector & remove_if

    The code above is wrong (twice decrementing of iterator).
    The code below is wrong, too: after erase() the iterator ivalid is no longer valid.
    You would have to do something like

    Qt Code:
    1. vector<double>::iterator ivalid = validValue.end() - 1;
    2. vector<bool>::iterator imask = _indexMissedMask.end() - 1;
    3. for ( ; imask != _indexMissedMask.begin(); --imask)
    4. {
    5. vector<double>::iterator tmp = ivalid;
    6. --tmp;
    7. if ( *imask )
    8. validValue.erase(ivalid); // invalidates ivalid; would return iterator pointing behind it
    9. ivalid=tmp;
    10. }
    To copy to clipboard, switch view to plain text mode 
    (untested, of course)

    This is why you should not reinvent the wheel yourself. Use the algorithms.

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.