multimap::emplace() in C++ STL

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of multimap::emplace() function in C++ STL.

What is Multimap in C++ STL?

Multimaps are the associative containers, which are similar to map containers. It also facilitates to store the elements formed by a combination of key value and mapped value in a specific order. In a multimap container there can be multiple elements associated with the same key. The data is internally always sorted with the help of its associated keys.

What is multimap::emplace()?

multimap::emplace() function is an inbuilt function in C++ STL, which is defined in <map> header file. emplace() is used to construct and inset a new element in multimap containers. This function effectively increases the size of the container by 1.

This function is similar to the insert function which copies or moves the object to insert the element in the container.

Syntax

multimap_name.emplace(Args& val);

Parameters

The function accepts following parameter(s)−

  • val − This is the element which we want to insert.

Return value

This function returns an iterator to the position of where the element is emplaced/inserted.

Input 

std::multimap<char, int> odd, eve;
odd.insert({‘a’, 1});
odd.emplace({‘b’, 3});

Output 

Odd: a:1 b:3

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   //create the container
   multimap<int, int> mul;
   //insert using emplace
   mul.emplace(1, 10);
   mul.emplace(4, 20);
   mul.emplace(5, 30);
   mul.emplace(2, 40);
   mul.emplace(3, 50);
   mul.emplace(4, 60);
   cout << "\nElements in multimap is : \n";
   cout << "KEY\tELEMENT\n";
   for (auto i = mul.begin(); i!= mul.end(); i++){
      cout << i->first << "\t" << i->second << endl;
   }
   return 0;
}

Output

If we run the above code it will generate the following output −

Elements in multimap is :
KEY ELEMENT
1 10
2 40
3 50
4 20
4 60
5 30
raja
Published on 22-Apr-2020 11:44:36
Advertisements