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

前端 未结 5 1042
情歌与酒
情歌与酒 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:31

    You need to be careful because erase() will invalidate existing iterators. However, it will return a new valid iterator you can use:

    for ( it = Entities.begin(); it != Entities.end(); ) {
       if( (*it)->getXPos() > 1.5f ) {
          delete * it;  
          it = Entities.erase(it);
       }
       else {
          ++it;
       }
    }
    

提交回复
热议问题