To create a Set of Sets in C++, you can use nested std::unordered_set containers. You create individual sets using std::unordered_set and then add them to another std::unordered_set.
In this example,
<unordered_set>
.set1
, set2
, and set3
using std::unordered_set
. We insert the elements 1, 2, 3
into set1
, 4, 5, 6
into set2
, and 7, 8, 9
into set3
.setOfSets
using std::unordered_set
, and we insert set1
, set2
, and set3
into setOfSets
. This nests the three sets within a single set.setOfSets
using a range-based for loop. Within the loop, we print each individual set to the standard output.#include <iostream>
#include <unordered_set>
int main() {
std::unordered_set<int> set1 = {1, 2, 3};
std::unordered_set<int> set2 = {4, 5, 6};
std::unordered_set<int> set3 = {7, 8, 9};
std::unordered_set<std::unordered_set<int>> setOfSets = {set1, set2, set3};
for (const auto& set : setOfSets) {
for (const auto& element : set) {
std::cout << element << " ";
}
std::cout << std::endl;
}
return 0;
}
Output: 1 2 3 4 5 6 7 8 9
In this example,
<unordered_set>
.setA
, setB
, and setC
using std::unordered_set
. We insert the strings "apple", "banana", "cherry"
into setA
, "dog", "elephant", "fox"
into setB
, and "grape", "honeydew", "kiwi"
into setC
.setOfStringSets
using std::unordered_set
, and we insert setA
, setB
, and setC
into setOfStringSets
. This nests the three sets within a single set.setOfStringSets
using a range-based for loop. Within the loop, we print each individual set to the standard output.#include <iostream>
#include <unordered_set>
#include <string>
int main() {
std::unordered_set<std::string> setA = {"apple", "banana", "cherry"};
std::unordered_set<std::string> setB = {"dog", "elephant", "fox"};
std::unordered_set<std::string> setC = {"grape", "honeydew", "kiwi"};
std::unordered_set<std::unordered_set<std::string>> setOfStringSets = {setA, setB, setC};
for (const auto& set : setOfStringSets) {
for (const auto& element : set) {
std::cout << element << " ";
}
std::cout << std::endl;
}
return 0;
}
Output: apple cherry banana fox dog elephant honeydew grape kiwi
In this tutorial, we learned How to create a Set of Sets in C++ language with well detailed examples.