To filter elements of a list based on a condition in C++, you can use the remove_if algorithm along with a lambda expression.
In this example,
numbers
with integer values.remove_if
algorithm along with a lambda expression to remove elements that do not satisfy the condition.erase
method to erase the removed elements.#include <iostream>
#include <list>
#include <algorithm>
int main() {
std::list<int> numbers = {1, 2, 3, 4, 5};
int threshold = 3;
numbers.remove_if([&threshold](int num) { return num <= threshold; });
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
4 5
In this example,
words
with string values.remove_if
algorithm along with a lambda expression to remove elements that do not satisfy the condition.erase
method to erase the removed elements.#include <iostream>
#include <list>
#include <algorithm>
#include <string>
int main() {
std::list<std::string> words = {"apple", "banana", "cherry", "date", "elderberry"};
std::string substring = "erry";
words.remove_if([&substring](const std::string& word) { return word.find(substring) == std::string::npos; });
for (const std::string& word : words) {
std::cout << word << " ";
}
return 0;
}
cherry elderberry
In this tutorial, we learned How to Filter Elements of a List based on a Condition in C++ language with well detailed examples.