Remove empty elements from a vector of strings in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <string> #include <vector> #include <algorithm> int main() { std::vector<std::string> v = { "A", "", "B", " ", "C", "\t", "D" }; auto isEmptyOrBlank = [](const std::string &s) { return s.find_first_not_of(" \t") == std::string::npos; }; v.erase(std::remove_if(v.begin(), v.end(), isEmptyOrBlank), v.end()); for (const auto &s : v ) { std::cout << s << ' '; } return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <string> #include <vector> #include <algorithm> int main() { std::vector<std::string> v = { "A", "", "B", " ", "C", "\t", "D" }; std::erase_if(v, [](const auto &s){ return s.find_first_not_of(" \t") == std::string::npos; }); for (const auto &s : v ) { std::cout << s << ' '; } return 0; } |
Output:
A B C D
That’s all about removing empty elements from a vector of strings in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)