set::emplace() in C++ with examples

In this tutorial, we will learn about set::emplace() function available in C++.

set::emplace()

We will cover these:

  • Basic function of set::emplace().
  • Syntax
  • Few examples
  • Actual implementation in C++ program.

Description

The function of set emplace() is to insert the new element in the container, only if the element is unique. It will not be inserted if the element is already present in the container.

Syntax

 a            set < T> sn;
a             sn.emplace(T element);

Examples

Input1    :   t{ 1 , 2 , 3 , 4 }
a                 t.emplace(6)
Output1 :   t{ 1 , 2 , 3 , 4 , 6 }

Input2   :  t{ 1 , 2 , 3 , 4 }
a               t.emplace(2)
Output2 :  t{ 1 , 2 , 3 , 4 }

Parameters
The element to be inserted into the set i.e. T element (where T is datatype).

Return
emplace function returns a boolean value i.e. if the element is successfully inserted into the set it returns true or else false.

Now we will implement it in C++

#include <iostream> 
#include <set> 
#include <string>
using namespace std; 

int main() 
{ 
    //Integer set example
  set<int> set1{}; 
  set1.emplace(1); 
  set1.emplace(3); 
  set1.emplace(9); 
  set1.emplace(4); 
  set1.emplace(0); 

  set1.emplace(6); //8 is unique in set so it will be inserted.
  
  set1.emplace(1); //1 is already present in set so it will not be inserted.
  
  cout<<"Integer Set : ";

  for (auto i = set1.begin() ; i != set1.end(); ++i) 
    cout << ' ' << *i; 
  
  //String set example
  set<string> set2{}; 
  set2.emplace("welcomes"); 
  set2.emplace("CodeSpeedy.com"); 
  
  set2.emplace("you."); //you. is unique in set so it will be inserted.
  
  set2.emplace("welcomes"); //welcome is already present in set so it will not be inserted.
  
  cout<<"\nString Set : ";

  for (auto i = set2.begin() ; i != set2.end(); ++i) 
    cout << ' ' << *i; 
  
  return 0;
} 

Output:

Integer Set :  0 1 3 4 6 9
String Set :  CodeSpeedy.com welcomes you.

Also read,

Leave a Reply

Your email address will not be published. Required fields are marked *