How to Add an Element to a Set in C++?
Last Updated :
26 Feb, 2024
Improve
In C++ STL, a set is a container that stores unique elements in a sorted order. In this article, we will learn how to add an element to a set in C++ STL.
Example:
Input: mySet = {1, 2, 4, 5, 8} Element to add: 3 Output: mySet = {1, 2, 3, 4, 5, 8}
Add an Element to a Set in C++
To add a specific element to a std::set in C++, we can use the std::set::insert() function. This function takes a value as an argument and inserts it into the set and maintains the set’s sorted order.
C++ Program to Add an Element to a Set
// CPP program to add an element to a Set
#include <iostream>
#include <set>
using namespace std;
// Driver Code
int main()
{
set<int> mySet = { 1, 2, 4, 5, 6 };
// Adding element 3 to the set using insert() function
mySet.insert(3);
// Displaying the elements of the set
for (int elem : mySet) {
cout << elem << " ";
}
return 0;
}
// This code is contributed by Susobhan Akhuli
Output
1 2 3 4 5 6
Time Complexity: O(log n), where n is the number of elements in the set.
Auxiliary Space: O(1)
We can also elements to the set by using the emplace() function.