In C++, you can use the standard library's set data structure to create a set of integers.
In this example,
<set>
header for using the std::set
data structure.numberSet
to store integers.insert()
method.#include <iostream>
#include <set>
int main() {
// Define a set of integers
std::set<int> numberSet;
// Insert integers into the set
numberSet.insert(1);
numberSet.insert(2);
numberSet.insert(3);
numberSet.insert(4);
numberSet.insert(5);
// Print the set
std::cout << "{ ";
for (const auto &num : numberSet) {
std::cout << num;
if (num != *numberSet.rbegin()) {
std::cout << ", ";
}
}
std::cout << " }";
return 0;
}
{ 1, 2, 3, 4, 5 }
In this example,
<unordered_set>
header for using the std::unordered_set
data structure.numberSet
to store integers.insert()
method.#include <iostream>
#include <unordered_set>
int main() {
// Define an unordered set of integers
std::unordered_set<int> numberSet;
// Insert integers into the set
numberSet.insert(1);
numberSet.insert(2);
numberSet.insert(3);
numberSet.insert(4);
numberSet.insert(5);
// Print the set
std::cout << "{ ";
for (const auto &num : numberSet) {
std::cout << num;
if (num != *numberSet.begin()) {
std::cout << ", ";
}
}
std::cout << " }";
return 0;
}
{ 1, 2, 3, 4, 5 }
In this tutorial, we learned How to create a Set of integers in C++ language with well detailed examples.