In C++, you can use STL algorithms like `remove_if` to remove elements based on a condition.
In this example,
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 6, 2, 7, 3, 8, 4, 9, 5};
numbers.erase(std::remove_if(numbers.begin(), numbers.end(), [](int num) { return num > 5; }), numbers.end());
std::cout << "Vector after filtering: ";
for (int num : numbers) {
std::cout << num << ' ';
}
return 0;
}
Vector after filtering: 1 2 3 4 5
In this example,
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<std::string> words = {"Apple", "Banana", "Apricot", "Grape", "Mango"};
words.erase(std::remove_if(words.begin(), words.end(), [](const std::string& word) { return word.front() == 'A'; }), words.end());
std::cout << "Vector after filtering: ";
for (const std::string& word : words) {
std::cout << word << ' ';
}
return 0;
}
Vector after filtering: Banana Grape Mango
In this tutorial, we learned How to Remove Element from Array based on a Condition in C++ language with well detailed examples.