To get a sub Set in C++, you can use the std::vector's erase-remove idiom or use iterator-based slicing.
In this example,
mySet
containing elements of a specific type.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// Define vector with items
std::vector<std::string> mySet = {"apple", "banana", "orange", "grape", "melon"};
// Get sub Set with items (Erase-Remove Idiom)
mySet.erase(std::remove_if(mySet.begin(), mySet.end(), [](const std::string& element) {
return element != "banana" && element != "orange" && element != "grape";
}), mySet.end());
// Print sub Set
for (const auto& item : mySet) {
std::cout << item << " ";
}
std::cout << std::endl;
return 0;
}
banana orange grape
In this example,
mySet
containing elements of a specific type.#include <iostream>
#include <vector>
int main() {
// Define vector with items
std::vector<std::string> mySet = {"apple", "banana", "orange", "grape", "melon"};
// Get sub Set with items (Iterator-Based Slicing)
std::vector<std::string> subSet(mySet.begin() + 1, mySet.begin() + 4);
// Print sub Set
for (const auto& item : subSet) {
std::cout << item << " ";
}
std::cout << std::endl;
return 0;
}
banana orange grape
In this example,
mySet
.#include <iostream>
#include <vector>
int main() {
// Define empty vector
std::vector<std::string> mySet;
// Get sub Set from empty vector
std::vector<std::string> subSet(mySet.begin() + 1, mySet.begin() + 4);
// Print sub Set
for (const auto& item : subSet) {
std::cout << item << " ";
}
std::cout << std::endl;
return 0;
}
In this tutorial, we learned How to get Subset from a Set in C++ language with well detailed examples.