C++ unordered_map insert

Introduction

To insert an element into a map we can use the member function .insert() member function:

#include <iostream> 
#include <unordered_map> 

int main() /* w w w.ja va2  s . c  om*/
{ 
     std::unordered_map<char, int> myunorderedmap = { {'a', 1}, {'b', 2},  
     {'c', 5} }; 
    myunorderedmap.insert({ 'd', 10 }); 

    for (auto el : myunorderedmap) 
    { 
        std::cout << el.first << ' '<< el.second << '\n'; 
    } 
} 

We can also use the map's operator [] to insert an element.

Normally, this operator is used to access an element value by key.

However, if the key does not exist, the operator inserts a new element into the map:

#include <iostream> 
#include <unordered_map> 

int main() /*from ww  w.j  a  va2 s  . c  om*/
{ 
     std::unordered_map<char, int> myunorderedmap = { {'a', 1}, {'b', 2},  
     {'c', 5} }; 
    myunorderedmap['b'] = 4; // key exists, change the value 
    myunorderedmap['d'] = 10; // key does not exist, insert the new element 
    for (auto el : myunorderedmap) 
    { 
        std::cout << el.first << ' ' << el.second << '\n'; 
    } 
} 



PreviousNext

Related