How to Add Multiple Elements to a Set in C++?
Last Updated :
22 Feb, 2024
In C++, a set is a container that stores the unique elements in a sorted order. In this article, we will learn how to add multiple elements to a set in C++.
For Example,
Input:
mySet = {1, 5, 6, 7, 8}
Elements to add: {1, 2, 3, 4, 5}
Output:
Set Elements are: 1 2 3 4 5
Insert Multiple Elements in a Set in C++
To add multiple elements to a std::set in one go, we can pass an initializer list of elements in the std::set::insert() function using the below syntax:
Syntax to Insert Multiple Elements in Set
setName.insert({elem1,elem2,elem3,elem4});
C++ Program to Add Multiple Elements to a Set
The below example demonstrates the use of the initializer list and insert() function to add multiple elements in a set.
C++
#include <iostream>
#include <set>
using namespace std;
int main()
{
set< int > mySet;
mySet.insert({ 10, 20, 30, 40, 50 });
cout << "Elements in set are:" << endl;
for ( const auto & element : mySet) {
cout << element << " " ;
}
return 0;
}
|
Output
Elements in set are:
10 20 30 40 50
Time Complexity: O(n log(n)), here n is the number of elements to be inserted in the set.
Auxilliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...