This post will discuss how to remove empty elements from a vector of strings in C++.

1. Using Erase-remove idiom

The recommended way to remove empty elements from a vector is using the Erase-remove idiom. Since the std::remove_if algorithm does not know the underlying container, it cannot remove elements from it. Only a call to the vector::erase algorithm actually removes elements.

A typical implementation of this approach would look like below:

Download  Run Code

Output:

A B C D

2. Using std::erase_if

Since C++20, we can use the std::erase_if algorithm to remove all elements from the vector satisfying a predicate. It is defined in header <vector> and acts as a wrapper over the Erase-remove idiom.

The following code example shows invocation for this method:

Download Code

Output:

A B C D

That’s all about removing empty elements from a vector of strings in C++.