How to remove vector elements in a loop?

This is something that has always bugged me. There has been many instance in my game engine development where I needed to delete elements of a C++ vector by using a loop. I always ended up crashing the engine. I always wondered: How can you remove elements in a vector using a loop without it crashing?

The solution is to use what is called the Erase-Remove idiom. It essentially consist of using two algorithms from the STL library:

  • Erase
  • Remove

So this is how it works:

Suppose you have the following vector:

std::vector<int> v={0,1,5,3,4,5,6,5,8,9};

Let's say that you want to remove all elements of the vector equal to 5. To do so, you will concatinate the two algorithms as such:

v.erase(std::remove(v.begin(),v.end(),5),v.end());

The above method will remove all elements in the vector equal to 5.

So, what if you want to have a function that test if an element is 5. For example:

bool isFive(int x){

    if (x==5) {
        return true;
    }else{
        return false;
    }
}

How would you be able to incorporate this function in the algorithm above? For that you will use the remove_if algorithm. For example

v.erase(std::remove_if(v.begin(),v.end(),isFive),v.end());

This will remove all elements equal to 5.

So, whenever you want to remove elements in a loop use the Erase-Remove idiom.

Hope it helps.

Sign up to my newsletter to get Game Engine Development and C++ tips.

Harold Serrano

Computer Graphics Enthusiast. Currently developing a 3D Game Engine.