To remove items from a set based on a condition in C++, you can use the std::remove_if
function along with a lambda expression and then erase the unwanted elements from the set.
In this example,
<iostream>
, <set>
, and <algorithm>
for the necessary functionalities.std::set<int>
named number_set
and initialize it with the values {1, 2, 3, 4, 5}
.[](int x) { return x % 2 == 0; }
checks if a number is even.std::remove_if
algorithm to rearrange the elements in the set such that the elements to be removed are moved to the end. However, since std::remove_if
does not work directly with sets due to their nature of having unique and ordered elements, we need to use a loop and the erase
method directly.erase
method.#include <iostream>
#include <set>
#include <algorithm>
int main() {
std::set<int> number_set = {1, 2, 3, 4, 5};
for(auto it = number_set.begin(); it != number_set.end(); ) {
if (*it % 2 == 0) {
it = number_set.erase(it);
} else {
++it;
}
}
for(const int &num : number_set) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
1 3 5
In this example,
<iostream>
, <set>
, and <string>
for the necessary functionalities.std::set<std::string>
named string_set
and initialize it with the values {"apple", "banana", "cherry", "date", "grape"}
.[](const std::string& s) { return s.length() < 6; }
checks if a string's length is less than 6.erase
method.#include <iostream>
#include <set>
#include <string>
int main() {
std::set<std::string> string_set = {"apple", "banana", "cherry", "date", "grape"};
for(auto it = string_set.begin(); it != string_set.end(); ) {
if (it->length() < 6) {
it = string_set.erase(it);
} else {
++it;
}
}
for(const std::string &str : string_set) {
std::cout << str << " ";
}
std::cout << std::endl;
return 0;
}
banana cherry
In this tutorial, we learned How to Remove Items from Set based on a Condition in C++ language with well detailed examples.