Unordered Map

#include <unordered_map>  

unordered_map<string, int> umap;                            // create a map of string: {integer}

// create a map with few initial elements 
unordered_map<string, int> umap = {
                                     {"batman", 100}, 
                                     {"superman", 500}, 
                                     {"shaktiman", 200}
                                  };     


cout << umap.size() << endl;                                // number of enteries in myMap
umap["spiderman"] = 150;                                    // add entry to the map

int bmMarks = umap.at("batman");                            // get a value in map corresponding to a key
int smMarks = umap["superman"];

umap.erase("superman");                                     // erase an entry from the map
umap.clear();                                               // remove all the enteries from the map

// check whether map is empty
if(umap.empty()){
    ...
}

// search for an element
if (umap.find("shaktiman") != umap.end()) {
    // It means key: "shaktiman" exists in the map
}

// iterate over all elements
for(unordered_map<string, int>::iterator it = umap.begin(); it != umap.end(); it++) {
    cout << *it << endl;
    cout << it->first << endl;
    cout << it->second << endl;
}
  

Last updated