map emplace_hint() function in C++ STL

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of map::emplace_hint() 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 map::emplace_hint()?

The map::emplace_hint( ) is a function which comes under  header file. This function constructs and inserts an element with a hint into the associated map container.

emplace_hint() 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 key of the value which is to be inserted.

Syntax

map_name.emplace_hint(iterator it, Args&& args);

Parameters

This function accepts the following parameters −

it − An iterator which can be considered as the hint of the position of the element which is to be inserted.

args − The arguments or values which we want to emplace at the position “it”.

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.

Example

Input

map<char, int> newmap;
emplace_hint(newmap.end(), ‘a’, 1);

Output

a

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_Map;
   TP_Map.emplace_hint(TP_Map.begin(), 4, 50);
   TP_Map.emplace_hint(TP_Map.begin(), 2, 30);
   TP_Map.emplace_hint(TP_Map.begin(), 1, 10);
   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
raja
Published on 15-Apr-2020 11:50:57
Advertisements