C++ map emplace() function

C++ map emplace() function is used to extend the map container by inserting new elements into the container. Elements are built directly (neither copied nor moved).

The constructor of the element is called by giving the arguments args passed to this function. Insertion takes place only, if the key is not present already.

Syntax

Parameter

args: The arguments forwarded to construct an element to be inserted into the map.

Return value

It returns a bool pair that will indicate if the insertion is occurred or not and returns an iterator pointing to the newly inserted element.

Example 1

Let's see a simple example to insert the elements into the map.

Output:

Map contains following elements
a = 1
b = 2
c = 3
d = 4
e = 5

In the above example, it simply inserts the element into the map m with the given key value pairs.

Example 2

Let's see a simple example to insert the element and check for the duplicate key.

Output:

  map modified, now contains 
3 elements: (10, ten) (20, twenty) (30, thirty) 

Emplace failed, element with key 10 already exists.
  The existing element is (10, ten)

In the above example, elements are inserted in the map and when you try to use the same key 10 then it will display an error message that key 10 already exists.

Example 3

Let's see a simple example to insert the elements into the map by passing a constructor argument to a key and a value respectively.

Output:

a => a
b => abcd
c => cccccccccc
d => ddd

In the above example, elements are inserted into the map by passing a constructor argument to a key and a value respectively.

Example 4

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

Output:

Enter the number of fmly members : 3
Enter the name and age of each member: 
Ram 42
Sita 37
Laxman 40

Total memnber of fmly is:3
Details of fmly members: 

Name    |  Age 
__________________________
Laxman | 40 
Ram      | 42 
Sita       | 37

In the above example, it simply inserts the elements by the user?s choice.

Next TopicC++ Map



Latest Courses