Proper vector memory management

后端 未结 6 1158
情歌与酒
情歌与酒 2021-02-15 11:56

I\'m making a game and I have a vector of bullets flying around. When the bullet is finished, I do bullets.erase(bullets.begin() + i); Then the bullet disappears. However it doe

6条回答
  •  囚心锁ツ
    2021-02-15 12:20

    When the bullet is finished, I do bullets.erase(bullets.begin() + i);

    Don't do that. If multiple bullets are finished per frame, you get horrible performance, because the bullets that aren't finished will get copied over and over, which really isn't necessary. Here is what I would do:

    #include 
    #include 
    #include 
    
    class Bullet
    {
        // ...
    public:
        bool is_finished() const;
    };
    
    int main()
    {
        std::vector bullets;
        // ...
        bullets.erase(
            std::remove_if(
                bullets.begin(),
                bullets.end(),
                std::mem_fun_ref(&Bullet::is_finished)
            ),
            bullets.end()
        );
    }
    

    This approach only moves each live bullet at most once.

提交回复
热议问题