Home »
C++ STL
set::emplace() function in C++ STL
C++ STL set::emplace() function: Here, we are going to learn about the emplace() function of set in C++ STL (Standard Template Library).
Submitted by Radib Kar, on February 16, 2019
C++ STL set::emplace() function
set::emplace() function is a predefined function, it is used to insert a new element to the set, if element is unique.
Prototype:
set<T> st; //declaration
st.emplace(T item);
Parameter: T item; //T is the data type
Return type: If it successfully inserts then it returns a pair<Iterator pointer to the inserted value, True>, Else It returns a pair<iterator to the existing value in the set, False>
Usage: The function inserts unique elements to the set.
Example:
For a set of integer,
set<int> st;
st.emplace(5);
st.emplace(4);
set content: //sorted always(ordered)
4
5
st.emplace(5) //no insertion this time
set content:
4
5
Header file to be included:
#include <iostream>
#include <set>
OR
#include <bits/stdc++.h>
C++ implementation:
#include <bits/stdc++.h>
using namespace std;
void printSet(set<int> st){
set<int>:: iterator it;
cout<<"Set contents are:\n";
if(st.empty()){
cout<<"empty set\n";
return;
}
for(it=st.begin();it!=st.end();it++)
cout<<*it<<" ";
cout<<endl;
}
int main(){
cout<<"Example of emplace function\n";
set<int> st;
set<int>:: iterator it;
cout<<"inserting 4\n";
st.emplace(4);
cout<<"inserting 6\n";
st.emplace(6);
cout<<"inserting 10\n";
st.emplace(10);
printSet(st); //printing current set
return 0;
}
Output
Example of emplace function
inserting 4
inserting 6
inserting 10
Set contents are:
4 6 10