How to erase & delete pointers to objects stored in a vector?

前端 未结 5 1004
情歌与酒
情歌与酒 2020-12-02 10:17

I have a vector that stores pointers to many objects instantiated dynamically, and I\'m trying to iterate through the vector and remove certain elements (remove from vector

5条回答
  •  北海茫月
    2020-12-02 10:44

    The main problem is that most stl container iterators do not support adding or removing elements to the container. Some will invalidate all iterators, some will only invalidate an iterator that is pointing at an item that is removed. Until you get a better feeling for how each of the containers work, you will have to be careful to read the documentation on what you can and can't do to a container.

    stl containers don't enforce a particular implementation, but a vector is usually implemented by an array under the hood. If you remove an element at the beginning, all the other items are moved. If you had an iterator pointing to one of the other items it might now be pointing at the element after the old element. If you add an item, the array may need to be resized, so a new array is made, the old stuff copied over, and now your iterator is pointing to the old version of the vector, which is bad.

    For your problem it should be safe to iterate through the vector backwards and remove elements as you go. It will also be slightly faster, since you wont be moving around items that you are going to later delete.

    vector Entities;
    /* Fill vector here */
    vector::iterator it;
    for(it=Entities.end(); it!=Entities.begin(); ){
      --it;
      if(*(*it) > 1.5f){
       delete *it;
       it=Entities.erase(it);
      }
    }
    

提交回复
热议问题