Vector.erase(Iterator) causes bad memory access

前端 未结 4 610
借酒劲吻你
借酒劲吻你 2020-12-03 19:49

I am trying to do a Z-Index reordering of videoObjects stored in a vector. The plan is to identify the videoObject which is going to b

相关标签:
4条回答
  • 2020-12-03 20:01

    You cannot delete while iterating over the list because the iterator gets invalid. You should use the return iterator of Erase to set it to your current iterator.

    0 讨论(0)
  • 2020-12-03 20:03

    Beware, erasing elements one by one from a vector has quadratic complexity. STL to the rescue!

    #include <algorithm>
    #include <functional>
    
    videoObjects.erase(
        std::remove_if(
            std::bind2nd(
                std::mem_fun_ref(&videoObject::isInside),
                ofPoint(tcur.getX(), tcur.getY())
            ),
        ),
        videoObjects.end()
    );
    
    0 讨论(0)
  • 2020-12-03 20:05

    erase function returns the next valid iterator.

    You would have to make a while loop and do something like

    iterator = erase(...)
    

    with corresponding checks.

    0 讨论(0)
  • 2020-12-03 20:13

    You should do

    itVid = videoObjects.erase(itVid);
    

    Quote from cplusplus.com:

    [vector::erase] invalidates all iterator and references to elements after position or first.

    Return value: A random access iterator pointing to the new location of the element that followed the last element erased by the function call, which is the vector end if the operation erased the last element in the sequence.

    Update: the way you access the current element inside your condition looks rather strange. Also one must avoid incrementing the iterator after erase, as this would skip an element and may cause out-of-bounds errors. Try this:

    for(itVid = videoObjects.begin(); itVid != videoObjects.end(); ){
      if(itVid->isInside(ofPoint(tcur.getX(), tcur.getY()))){
        itVid = videoObjects.erase(itVid);
      } else {
        ++itVid;
      }
    }
    
    0 讨论(0)
提交回复
热议问题