To create a set of numbers from 1 to N in C++, you can use a loop to add elements to a set.
In this example,
numberSet
to store the numbers from 1 to 5.for
loop to iterate from 1 to 5 and add each number to the set.#include <iostream>
#include <set>
int main() {
std::set<int> numberSet;
for (int i = 1; i <= 5; ++i) {
numberSet.insert(i);
}
std::cout << "Set of numbers from 1 to 5:\n";
for (int num : numberSet) {
std::cout << num << ' ';
}
return 0;
}
Set of numbers from 1 to 5: 1 2 3 4 5
In this example,
numberSet
to store the numbers from 1 to 10.for
loop to iterate from 1 to 10 and add each number to the set.#include <iostream>
#include <set>
int main() {
std::set<int> numberSet;
for (int i = 1; i <= 10; ++i) {
numberSet.insert(i);
}
std::cout << "Set of numbers from 1 to 10:\n";
for (int num : numberSet) {
std::cout << num << ' ';
}
return 0;
}
Set of numbers from 1 to 10: 1 2 3 4 5 6 7 8 9 10
In this tutorial, we learned How to create a Set of Numbers from 1 to N in C++ language with well detailed examples.