To filter elements of an array based on a condition in C++, you can use standard algorithms like std::copy_if or std::remove_if.
In this example,
numbers
containing integers.evenNumbers
.#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
vector<int> evenNumbers;
std::copy_if(numbers.begin(), numbers.end(), std::back_inserter(evenNumbers), [](int num){ return num % 2 == 0; });
cout << "Even Numbers: ";
for (int num : evenNumbers) {
cout << num << " ";
}
return 0;
}
Even Numbers: 2 4 6 8 10
In this example,
words
containing strings.filteredWords
.#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> words = {"apple", "banana", "cherry", "date", "fig"};
vector<string> filteredWords;
std::copy_if(words.begin(), words.end(), std::back_inserter(filteredWords), [](const string& word){ return word.length() > 5; });
cout << "Filtered Words: ";
for (const string& word : filteredWords) {
cout << word << " ";
}
return 0;
}
Filtered Words: banana cherry
In this tutorial, we learned How to Filter Elements of an Array based on a Condition in C++ language with well detailed examples.