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++
// C++ program to add multiple elements in a set #include <iostream> #include <set> using namespace std; int main() { set< int > mySet; // Adding multiple elements using insert and initializer // list mySet.insert({ 10, 20, 30, 40, 50 }); // Displaying the set cout << "Elements in set are:" << endl; for ( const auto & element : mySet) { cout << element << " " ; } return 0; } |
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)
How to Add Multiple Elements to a Set in C++?
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