Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C++ flat_set::emplace() Function



The std::flat_set::emplace() function in C++, is used to efficiently insert a new element into a flat_set. Unlike the insert() function, emplace() constructs the element in place, avoiding unnecessary copies or moves.

The function takes the constructor arguments of the element type and inserts it while maintaining the set's sorted order. If the element is is already exists, then the insertion does not takes place.

Syntax

Following is the syntax for std::flat_set::emplace() function.

emplace( Args&&... args );

Parameters

  • args − It indicates the arguments to forward to the constructor of the element.

Return Value

This function returns a pair consisting of an iterator to the inserted element.

Example 1

Let's look at the following example, where we are going to insert the element into the flat_set.

#include <iostream>
#include <boost/container/flat_set.hpp>
int main() {
   boost::container::flat_set < int > x;
   x.emplace(112);
   for (const auto & elem: x) {
      std::cout << "Result : " << elem;
   }
   return 0;
}

Output

Output of the above code is as follows −

Result : 112

Example 2

Consider the following example, where we are going to avoid the insertion of duplicates using the emplace().

#include <iostream>
#include <boost/container/flat_set.hpp>
int main() {
   boost::container::flat_set < int > a;
   a.emplace(1);
   a.emplace(3);
   a.emplace(2);
   a.emplace(1);
   for (const auto & elem: a) {
      std::cout << elem << " ";
   }
   return 0;
}

Output

Output of the above code is as follows −

1 2 3
cpp_flat_set.htm
Advertisements