In this C++ tutorial, you shall learn how to remove empty strings from a vector, with example programs.

Remove empty String elements from Vector in C++

To remove empty string elements from a vector in C++, iterate over the elements of given vector, and if the current element is an empty string, delete the current element.

C++ Program

In the following program, we take a string vector in v, and remove the empty strings from it.

main.cpp

#include <iostream>
#include <vector>
using namespace std;

int main() {
   //initialize a vector
   vector<string> v { "apple", "", "banana", "", "", "" };
   
   //iterate over vector elements
   for (unsigned int i = 1 ; i < v.size(); ++i) {
      if ( v.at(i) == "" ) {
         //remove element if empty string
         v.erase(v.begin() + i);
         --i;
      }
   }

   //print vector elements
   for(auto& element: v) {
      cout << element << endl;
   }
}

Output

apple
banana
ADVERTISEMENT

Conclusion

In this C++ Tutorial, we learned how to remove elements that are empty strings from a given vector.