In this C++ tutorial, you shall learn how to remove elements in a given vector based on a condition, with example programs.
Remove elements from Vector based on a condition in C++
To remove elements in a vector based on a condition
- Iterate over the elements of given vector using index.
- If the condition is satisfied, delete the current element.
Examples
1. Remove negative numbers from vector
In the following program, we take an integer vector in v
, and remove the negative elements from it.
We use For loop to iterate over the elements of the vector, and If statement to compare the elements.
main.cpp
</>
Copy
#include <iostream>
#include <vector>
using namespace std;
int main() {
//initialize a vector
vector<int> v { 4, 0, -3, 2, -8, 1, -7 };
for (unsigned int i = 1 ; i < v.size(); ++i) {
if ( v.at(i) < 0 ) {
//remove element if negative
v.erase(v.begin() + i);
--i;
}
}
//print vector elements
for(auto& element: v) {
cout << element << " ";
}
}
Output
4 0 2 1
2. Remove empty strings from vector
In the following program, we take a string vector in v
, and remove the empty strings from it.
main.cpp
</>
Copy
#include <iostream>
#include <vector>
using namespace std;
int main() {
//initialize a vector
vector<string> v { "apple", "", "banana", "", "", "" };
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
Conclusion
In this C++ Tutorial, we learned how to remove elements from a given vector, based on a condition.