Different Ways to Initialize an Set in C++
Initializing a set means assigning some initial values to the elements of the set container. In this article, we will learn different methods to initialize an std::set in C++.
Table of Content
Using Initializer List
The most common method to initialize a std::set container is by using initializer list at the time of its declaration. An initializer list is a list of values enclosed inside braces {} and separated by a comma. As set is ordered container, it will arrange the elements of the initializer list according to the specified order.
Syntax
set<type> s = {v1, v2, v3, ...}
where v1, v2, v3, ... are values inside for initialization.
Example
// C++ Program to initialize std::set using
// intializer list
#include <bits/stdc++.h>
using namespace std;
int main() {
// Initialize a set
set<int> s = {11, 9, 7, 45};
for (auto i : s)
cout << i << " ";
return 0;
}
Output
7 9 11 45
If we want to initialize the set using initializer list after its declaration, we can pass this list to set::insert() method.
One by One Initialization
We can also initialize the set by inserting elements one by one using the set::insert() method. This method allows the insertion of the given value and maintains the order of the set.
Example
// C++ Program to initialize std::set by
// inserting elements one by one
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> s;
// Iniitalize set by inserting elements
// one by one
s.insert(11);
s.insert(9);
s.insert(7);
s.insert(45);
for (auto i : s)
cout << i << " ";
return 0;
}
Output
7 9 11 45
From Another std::set
In C++, we can initialize a set by copying all elements from an already existing set with the help of copy constructor.
Syntax
set<int> s2(s1);
where s1 and s2 are the two set containers.
Example
// C++ Program to initialize std::set
// from another std::set
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> s1 = {11, 9, 7, 45};
// Initialize a set using another set
set<int> s2 = (s1);
for (auto i : s2)
cout << i << " ";
return 0;
}
Output
7 9 11 45
From Another STL Container or Array
We can use the range constructor of set to initialize it from any STL container or even an array.
Syntax
set<int> s(first, last);
where, first and last are the iterator or pointer to the first element and the element just after the last element of the range.
Example
// C++ program to initialize a set
// from an array
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[]= {11, 9, 7, 45};
int n = sizeof(arr)/sizeof(arr[0]);
// Initializing a set from array
set<int> s(arr, arr + n);
for (int i : s)
cout << i << " ";
return 0;
}
Output
7 9 11 45