To remove items from a vector based on a condition in C++, you can use the erase
method along with the remove_if
algorithm.
In this example,
<vector>
and <algorithm>
.vec
and initialize it with some integer values.isLessThan30
that returns true
if the passed element is less than 30.remove_if
algorithm to shift all elements that satisfy the condition specified by the predicate function to the end of the vector.erase
method to remove the elements from the end to the actual end of the vector.#include <vector>
#include <algorithm>
#include <iostream>
bool isLessThan30(int x) {
return x < 30;
}
int main() {
std::vector<int> vec = {10, 20, 30, 40, 50};
vec.erase(std::remove_if(vec.begin(), vec.end(), isLessThan30), vec.end());
std::cout << "Vector after removing items based on condition: ";
for (int val : vec) {
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}
Vector after removing items based on condition: 30 40 50
In this example,
<vector>
and <algorithm>
.vec
and initialize it with some integer values.remove_if
algorithm with the lambda function to shift all elements that satisfy the condition to the end of the vector.erase
method to remove the elements from the end to the actual end of the vector.#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> vec = {10, 20, 30, 40, 50};
vec.erase(std::remove_if(vec.begin(), vec.end(), [](int x) { return x < 30; }), vec.end());
std::cout << "Vector after removing items based on condition: ";
for (int val : vec) {
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}
Vector after removing items based on condition: 30 40 50
In this tutorial, we learned How to Remove Items from Vector based on a Condition in C++ language with well detailed examples.