Tech Blogs
  • Vivek bhargav
  • Books
    • Seven Databases In Seven Weeks
      • Factors to consider
      • Genres of databases
      • Important questions
      • PostGreSQL
  • Tech
    • C++
      • Type Conversions
      • String
      • Vector
      • Set
      • Unordered Set
      • Map
      • Unordered Map
      • Queue
      • Priority Queue
      • Union find
      • Algorithms
      • Matrix to Graph
      • Trie
      • Dijkstra
      • Math
      • Utils
    • Database Transactions
      • A Simple Transaction Analysis
      • Implementation of Isolation Levels
      • Isolation Levels
      • Isolation
      • Storage Types
      • Transaction Atomicity and Durability
    • Java
      • Important Questions
      • Spring MVC
    • Program execution
      • Node.js
      • Runtimes
    • System Design
      • Basic Terminologies
      • CAP Theorem
      • Normalization of Database
      • Useful Reads
  • Personal Finance
    • Asset Classes
      • Equity instruments
      • Debt instruments
Powered by GitBook
On this page
  1. Tech
  2. C++

Map

#include <map>  

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

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


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

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

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

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

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

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

Last updated 2 years ago