To remove elements from a list in C++ using `std::list`, you can use the `remove_if` algorithm along with a lambda function.
In this example,
std::list
and algorithms.numbers
with some elements.remove_if
algorithm along with a lambda function to remove elements greater than the threshold.#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 x) { return x > threshold; });
for (const auto& num : numbers) {
std::cout << num << " ";
}
return 0;
}
1 2 3
In this example,
std::list
and algorithms.names
with some elements.is_long_name
that returns true
if the length of the string is greater than a specified value.remove_if
algorithm along with the is_long_name
predicate to remove elements matching the predicate condition.#include <iostream>
#include <list>
#include <algorithm>
bool is_long_name(const std::string& name, int max_length) {
return name.length() > max_length;
}
int main() {
std::list<std::string> names = {"John", "Alice", "Michael", "Emma"};
int max_length = 5;
names.remove_if([&max_length](const std::string& name) { return is_long_name(name, max_length); });
for (const auto& name : names) {
std::cout << name << " ";
}
return 0;
}
John Alice Emma
In this tutorial, we learned How to Remove Element from List based on a Condition in C++ language with well detailed examples.