Set Emplace Function - C++ Programming Tutorial
C++ Course / STL Set & Map / Set Emplace Function

Set Emplace Function

BLUF: Mastering Set Emplace Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Set Emplace Function

C++ is renowned for its efficiency. Learn how Set Emplace Function enables low-level control and high-performance computing in the tutorial below.

C++ set emplace

C++ set emplace method is employed to expand the set container by adding fresh elements directly into the container without copying or moving them.

The constructor of the element is invoked by providing the arguments args that are passed to this function.

Insertion occurs exclusively when the key is not already present.

Syntax

Example

template <class.... Args>
    pair<iterator, bool> emplace (Args&&... args);    //since C++ 11

Parameter

Parameters: The parameters passed to create an element that will be added to the set.

Return value

The emplace method provides a pair of booleans to signal whether the insertion took place and furnishes an iterator pointing to the newly added element.

Complexity

Logarithmic in the container size.

Iterator validity

No changes.

Data Races

The container is modified.

Traversing through ranges within the container poses a risk, whereas accessing existing elements concurrently is considered safe.

Exception Safety

If an error is raised, the container remains unchanged.

Example 1

Let's explore a basic illustration of adding elements to a set:

Example

#include <iostream>
#include <set>

using namespace std;

int main(void) {
   
   set<char> m;

   m.emplace('a');
   m.emplace('b');
   m.emplace('c');
   m.emplace('d');
   m.emplace('e');

   cout << "Set contains following elements" << endl;

   for (auto it = m.begin(); it != m.end(); ++it)
      cout << *it<< ", ";

   return 0;
}

Output:

Output

Set contains following elements
a, b, c, d, e,

In the aforementioned example, it merely adds the element to the set m using the provided key-value pairs.

Example 2

Let's explore a basic example to insert the element and validate for duplicate keys:

Example

#include <set>  
#include <string>  
#include <iostream>  
  
using namespace std;  
  
template <typename S> void print(const S& s) {  
    cout << s.size() << " elements: ";  
  
    for (const auto& p : s) {  
        cout << "(" << p << ") ";  
    }  
  
    cout << endl;  
}  
  
int main()  
{  
    set<string> s1;  
  
    auto ret = s1.emplace("ten");  
  
    if (!ret.second){  
        cout << "Emplace failed, element with value \"ten\" already exists."  
            << endl << "  The existing element is (" << *ret.first << ")"  
            << endl;  
        cout << "set not modified" << endl;  
    }  
    else{  
        cout << "set modified, now contains ";  
        print(s1);  
    }  
    cout << endl;  
  
    ret = s1.emplace("ten");  
  
    if (!ret.second){  
        cout << "Emplace failed, element with value \"ten\" already exists."  
            << endl << "  The existing element is (" << *ret.first << ")"  
            << endl;  
    }  
    else{  
        cout << "set modified, now contains ";  
        print(s1);  
    }  
    cout << endl;  
}

Output:

Output

set modified, now contains 1 elements: (ten) 

Emplace failed, element with value "ten" already exists.
  The existing element is (ten)

In the scenario mentioned, items are added to the set, and if an attempt is made to add an item with the key "ten" that already exists, an error message indicating the duplication of the key "ten" will be shown.

Example 3

Let's explore a basic illustration to calculate the total of the provided elements:

Example

#include <iostream>
#include <set>
using namespace std;
 
int main()
{
    // sum variable declaration
    int sum = 0;
 
    // set declaration
    set<int> myset{};
    myset.emplace(1);
    myset.emplace(7);
    myset.emplace(4);
    myset.emplace(8);
    myset.emplace(2);
    myset.emplace(5);
    myset.emplace(3);
 
    // iterator declaration
    set<int>::iterator it;
 
    // finding sum of elements
    while (!myset.empty()) {
        it = myset.begin();
        sum = sum + *it;
        myset.erase(it);
    }
 
    // printing the sum
    cout << "Sum of elements is: "<<sum;
    return 0;
}

Output:

Output

Sum of elements is: 30

Example 4

Let's see a simple example to insert the element:

Example

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

int main() {

  typedef set<string> city;  
   string name;
   city fmly ;
   int n;

   cout<<"Enter the number of family members :";
   cin>>n;

   cout<<"Enter the name of each member: \n";
   for(int i =0; i<n; i++)
   {
       cin>> name;      // Get key
       fmly.emplace(name);
       
   }
   
      cout<<"\nTotal member of family is:"<< fmly.size();

      cout<<"\nDetails of family members: \n";
      cout<<"\nName \n ________________________\n";
      city::iterator p;
      for(p = fmly.begin(); p!=fmly.end(); p++)
      {
          cout<<(*p)<<" \n ";
      }
    
   return 0;
}

Output:

Output

Enter the number of family members: 3
Enter the name of each member: 
Bob
Robin
David

Total member of family is: 3
Details of family members: 

Name 
 ________________________
Bob 
David 
Robin

In the example provided, it merely adds the elements based on the user's selection.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience