Open In App

Inserting elements in std::map (insert, emplace and operator [])

Last Updated : 14 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Map in STL

The map is a container, as the name suggests used to store a key-value pair. The map has an advantage over other containers by the fact that searching in the map, defined by the “key” takes only O(1) time complexity, hence making it useful in various coding fields. The insertion is discussed in this article.

1. Using insert(): Insert function is used to insert the key-value pair in the map. After insertion, the reordering of elements takes place and the map is sorted w.r.t the key. 

This function is implemented in 3 ways:

  • insert(pair): This function inserts the pair in the map. The insertion only takes place when the key passed is not already inset. 
    It returns a pointer pair. First element points to the pair already present or newly inserted. The second element returns the boolean status “true” or “false”. 
    Time complexity: log(n) where n is the size of the map
  • insert(hint, pair): In this implementation, the hint pointer is sent with the pair to be inserted. The use of a hint pointer is to help insert() know where the actual insertion has to take place. Hence, trying to reduce the time to allocate the pair. 
    Hint pointer does not force the insertion at a specific position. This function returns the pointer to the position where the pair is inserted. 
    Time complexity: log(n) where n is the size of the map if the hint is optimal then O(1)
  • insert(beg_ptr, end_ptr): This type of insertion is required to insert the pairs of other containers into the map. The repeated pairs are not inserted if they are present in the destination container. 
    Time complexity: k*log(n) where n is the size of the map, and k is no. of elements inserted.

C++




// C++ code to demonstrate the working of insert() 
    
#include<iostream> 
#include<map> // for map operations 
using namespace std; 
    
int main() 
    // declaring map 
    // of char and int 
    map< char, int > mp; 
        
    // declaring iterators 
    map<char, int>::iterator it ; 
    map<char, int>::iterator it1; 
    map<char, int>::iterator it2; 
        
    // declaring pair for return value of map containing 
    // map iterator and bool 
    pair <map<char, int>::iterator, bool> ptr; 
        
    // using insert() to insert single pair 
    // inserting 'a' with 20 
    ptr = mp.insert( pair<char, int>('a', 20) ); 
        
    // checking if the key was already present or newly inserted 
    if(ptr.second) 
        cout << "The key was newly inserted"
    else 
        cout << "The key was already present"
        
    cout << endl ; 
        
    // printing map pairs after insertion 
    cout << "The map pairs after 1st insertion are : \n"
        
    for (it1 = mp.begin(); it1!=mp.end(); ++it1) 
        cout << it1->first << "->" << it1->second << endl; 
        
    it = mp.begin(); 
        
    // inserting map pair using hint  
    mp.insert(it, pair<char, int>('b', 24) ); 
        
    cout << endl ; 
        
    // printing map pairs after insertion 
    cout << "The map pairs after 2nd insertion are : \n"
        
    for (it1 = mp.begin(); it1!=mp.end(); ++it1) 
        cout << it1->first << "->" << it1->second << endl; 
        
    // initializing another map  
    map<char, int> mp2; 
        
    // using insert(beg_iter, end_iter) to copy all elements 
    mp2.insert(mp.begin(), mp.end()); 
        
    cout << endl ; 
        
    // printing new map pairs after insertion 
    cout << "The new map pairs after insertion are : \n"
        
    for (it1 = mp2.begin(); it1!=mp2.end(); ++it1) 
        cout << it1->first << "->" << it1->second << endl; 
        
}


Output

The key was newly inserted
The map pairs after 1st insertion are : 
a->20

The map pairs after 2nd insertion are : 
a->20
b->24

The new map pairs after insertion are : 
a->20
b->24

2. Using emplace: emplace is also used to insert the pairs into the map. This function is similar to “insert()” discussed above, the only difference being that the “in-place” construction of the pair takes place at the position of element insertion contrary to insert() which copies or movies existing objects. 

  • emplace(): Inserts pairs using an in-place construction strategy. Increases the size of the map by 1. returns a pointer pair. 1st element of which is an iterator pointing to the position of inserted pair. 2nd returns a boolean variable indicating an already present or newly created pair.
    Time complexity: log(n) (n is the size of the map)
  • emplace_hint(): Takes a “hint_iterator” to get a hint of the position of insertion to possibly reduce the time required to insert the pair inserted. This does not affect the position of insertion. It takes place where it is defined internally.
    Time complexity: log(n) (n is the size of the map), if the hint is optimal then O(1)

C++




// C++ code to demonstrate the working of emplace() 
// and emplace_hint() 
#include<iostream> 
#include<map> // for map operations 
using namespace std; 
    
int main() 
    // declaring map 
    map<char, int> mp; 
        
    // declaring iterators 
    map<char, int>::iterator it; 
    map<char, int>::iterator it1; 
    map<char, int>::iterator it2; 
        
    // declaring pair for return value of map containing 
    // map iterator and bool 
    pair< map<char, int>::iterator, bool> ptr; 
        
    // using emplace() to insert pair element 
    // inserting 'a' to 24 
    // no "pair" needed, in-place construction 
    ptr = mp.emplace('a', 24); 
        
    // checking if the pair was already present or newly inserted 
    // returns true. newly inserted 
    if (ptr.second) 
        cout << "The key was newly inserted"
    else 
        cout << "The key was already present"
        
    cout << endl; 
        
    // printing map pairs after insertion 
    cout << "The map pairs after 1st insertion are : \n"
        
    for (it1 = mp.begin(); it1!=mp.end(); ++it1) 
        cout << it1->first << "->" << it1->second << endl; 
        
    cout << endl ; 
        
    // using emplace() to insert single pair 
    // inserting a to 24 // not inserted this time 
    ptr = mp.emplace('a', 24); 
        
    // checking if the key was already present or newly inserted 
    // returns false. already inserted 
    if(ptr.second) 
        cout << "The key was newly inserted"
    else 
        cout << "The key was already present"
        
    cout << endl ; 
        
    // printing map pairs after insertion 
    cout << "The map pairs after 2nd insertion are : \n"
        
    for (it1 = mp.begin(); it1!=mp.end(); ++it1) 
        cout << it1->first << "->" << it1->second << endl; 
        
    it = mp.begin(); 
        
    // inserting map pair using hint 
    mp.emplace_hint(it, 'b', 20); 
        
    cout << endl ; 
        
    // printing map pairs after insertion 
    cout << "The map pairs after 3rd insertion are : \n"
        
    for (it1 = mp.begin(); it1!=mp.end(); ++it1) 
        cout << it1->first << "->" << it1->second << endl; 
    
        
}


Output

The key was newly inserted
The map pairs after 1st insertion are : 
a->24

The key was already present
The map pairs after 2nd insertion are : 
a->24

The map pairs after 3rd insertion are : 
a->24
b->20

3. Using operator[]: “[]” can also be used to insert elements in the map. Similar to the above functions and returns the pointer to the newly constructed element. The difference is that this operator always constructs a new element i.e even if a value is not mapped to a key, the default constructor is called and assigns a “null” or “empty” value to the key. The size of the map is always increased by 1
Time complexity: log(n) where n is the size of the map

C++




// C++ code to demonstrate the working of operator[]
  
#include<iostream>
#include<map> // for map operations
using namespace std;
  
int main()
{
    // declaring map
    map<char, int> mp;
      
    // using [] to assign key to value 
    mp['a'] = 5;
    mp['b'] = 6;
    mp['c'] = 2;
      
    // printing values
    cout << "The element keys to a is : ";
    cout << mp['a'] << endl;
      
    cout << "The element keys to b is : ";
    cout << mp['b'] << endl;
      
    cout << "The element keys to c is : ";
    cout << mp['c'] << endl;
      
    // default constructor is called
    // prints 0
    cout << "The element keys to d is : ";
    cout << mp['d'] << endl;
      
      
}


Output

The element keys to a is : 5
The element keys to b is : 6
The element keys to c is : 2
The element keys to d is : 0

Note:

Difference between the two ways of inserting(Using operator[] & using insert()):

Both of these two methods work similarly when there is no duplicate key. 
The map has the characteristic of removing duplicate keys. 
Both methods follow this characteristic of the map and remove the key and it’s a co-responding element if the key is already there in the map. 
But in the case of the third method(using operator[]) when a new key is being inserted in the map which is already present in the map then it removes the already present key and its element while in the case of the first method(using insert()) it removes the new key and it’s an element that is being inserted.

Related Article: Searching in Map STL C++

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads