![]() |
A set is an associative container available in the C++ Standard Template Library(STL) that is used for unique elements in a specific order, it internally uses the working principle of a Binary Search Tree to store elements. Different Ways to Initialize a set in C++:
1. Initialization Using the Default ConstructorOne standard way to initialize a set is to initialize using the default constructor, this will generate an empty set. Elements can be added to it using an inbuilt set.insert() method. Syntax:
Here, the insert() method can be further used to insert elements into the set. Below is the C++ program to implement the above approach: C++
Output
1 2 3 5 7 Time Complexity : O(N logN) Auxiliary Space : O(N) 2. Initialization using an Initializer ListAnother way of initialization is to pass a predefined list of elements (initializer_list) as an argument to the default constructor of the set as shown below: Syntax:
Below is the C++ program to implement the above approach: C++
Output
0 2 3 4 6 9 3. Initialization Using an ArrayThe elements can be added to the set using an array of the same data type. Syntax:
Here, old_arr is the array of integers from which contents will be copied into the New_set. Below is the C++ program to implement the above approach: C++
Output
1 3 4 6 8 4. Initialization Using a VectorOne can store the elements to the set using a vector of the same data type. Syntax:
Here, old_vector is the vector of integers from which contents will be copied into the New_set. Below is the C++ program to implement the above approach: C++
Output
Table Cement Floor Grass Ground 5. Initialization From Another Set Using the Copy ConstructorOne way to initialize a set is to copy contents from another set one after another by using the copy constructor. Syntax:
Here, old_set is the set from which contents will be copied into the New_set Below is the C++ program to implement the above approach: C++
Output
1 2 3 4 5 6. Initialization From Another Iterable Data Structure Using Range ConstructorAnother way to initialize a set is to use a range constructor to copy elements from an iterable data structure to the newly initialized set. Syntax:
Here, old_set is the set from which contents will be copied into the New_set. Below is the C++ program to implement the above approach: C++
Output
1 3 4 5 8 |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |