To filter items of a set based on a condition in C++, you can use the std::copy_if algorithm with a lambda function as the filtering predicate to create a new set from the filtered items.
In this example,
numberSet
using the std::unordered_set
container, which contains integer values 1
, 5
, 10
, 15
, and 20
.filteredSet
of the same type and size as numberSet
.std::copy_if
algorithm with a lambda function as the filtering predicate to copy the numbers greater than 5 from numberSet
to filteredSet
.filteredSet
and print each filtered item to the console.#include <iostream>
#include <unordered_set>
#include <algorithm>
int main() {
std::unordered_set<int> numberSet = {1, 5, 10, 15, 20};
std::unordered_set<int> filteredSet(numberSet.size());
std::copy_if(numberSet.begin(), numberSet.end(), filteredSet.begin(), [](int num) { return num > 5; });
for (int num : filteredSet) {
std::cout << num << std::endl;
}
return 0;
}
10 15 20
In this example,
stringSet
using the std::unordered_set
container, which contains string values "apple"
, "banana"
, "cherry"
, "date"
, and "grape"
.filteredStringSet
of the same type and size as stringSet
.std::copy_if
algorithm with a lambda function as the filtering predicate to copy the strings containing the letter 'a' from stringSet
to filteredStringSet
.filteredStringSet
and print each filtered string to the console.#include <iostream>
#include <unordered_set>
#include <algorithm>
#include <string>
int main() {
std::unordered_set<std::string> stringSet = {"apple", "banana", "cherry", "date", "grape"};
std::unordered_set<std::string> filteredStringSet(stringSet.size());
std::copy_if(stringSet.begin(), stringSet.end(), filteredStringSet.begin(), [](const std::string& str) { return str.find('a') != std::string::npos; });
for (const std::string& str : filteredStringSet) {
std::cout << str << std::endl;
}
return 0;
}
apple banana grape
In this tutorial, we learned How to Filter Items of a Set based on a Condition in C++ language with well detailed examples.