
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Map Emplace in C++ STL
In this article we will be discussing the working, syntax and examples of map::emplace() function in C++ STL.
What is a Map in C++ STL?
Maps are the associative container, which facilitates to store the elements formed by a combination of key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in the map container are accessed by its unique keys.
What is a map::emplace()?
The map::emplace( ) is a function which comes under <map> header file. This function constructs and inserts an element into the associated map container.
emplace() inserts the new element if the key of the element which is to be emplaced is unique. The insertion only happens if there is no element with the same key of the value which is to be inserted. This function works the same as insert() which copies and moves the existing object into the container.
If the element is successfully inserted the size of the container is increased by 1
Syntax
map_name.emplace(Args&& args);
Parameters
This function accepts the following parameter −
args − The arguments or values which we want to be emplaced or inserted.
Return value
If the insertion is successful then the function returns the iterator pointing to the new element which is inserted. Else it returns the iterator to equivalent value which is already present in the container.
Input
map<char, int> newmap; emplace( ‘a’, 1);
Output
a
Example
#include <bits/stdc++.h> using namespace std; int main() { map<int, int> TP_Map; TP_Map.emplace(4, 50); TP_Map.emplace(2, 30); TP_Map.emplace(1, 10); TP_Map.emplace(1, 20); TP_Map.emplace(1, 30); cout<<"TP Map is : \n"; cout << "MAP_KEY\tMAP_ELEMENT\n"; for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++) cout << i->first << "\t" << i->second << endl; return 0; }
Output
TP Map is: MAP_KEY MAP_ELEMENT 1 10 2 30 4 50