How to Add an Element to a Set in C++?
Last Updated :
26 Feb, 2024
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
C++
#include <iostream>
#include <set>
using namespace std;
int main()
{
set< int > mySet = { 1, 2, 4, 5, 6 };
mySet.insert(3);
for ( int elem : mySet) {
cout << elem << " " ;
}
return 0;
}
|
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.
Share your thoughts in the comments
Please Login to comment...