Skip to content

Map Structures

Harshal Agarwal edited this page Mar 6, 2022 · 2 revisions

Map Structures

A map is a generalized array that consists of key-value-pairs. While the keys in an ordinary array are always the consecutive integers 0,1,...,n−1, where n is the size of the array, the keys in a map can be of any data type and they do not have to be consecutive values.

The following code creates a map where the keys are strings and the values are integers:

       map<string,int> m;
       m["monkey"] = 4;
       m["banana"] = 3;
       m["harpsichord"] = 9;
       cout << m["banana"] << "\n"; // 3

If the value of a key is requested but the map does not contain it, the key is automatically added to the map with a default value. For example, in the following code, the key ”iecse” with value 0 is added to the map.

      map<string,int> m;
      cout << m["iecse"] << "\n"; // 0

The function count checks if a key exists in a map:

      if (m.count("iecse")) {
       // key exists
      }

The following code prints all the keys and values in a map:

      for (auto x : m) {
      cout << x.first << " " << x.second << "\n";
      }

JAVA EQUIVALENT

Map interface is present in the java.util package which can be accessed as follows:

      import java.util.*; 

A map can be created as shown below:

      Map<String, Integer> hm  = new HashMap<String, Integer>(); 
      hm.put("a", new Integer(100)); 
      hm.put("b", new Integer(200)); 
      hm.put("c", new Integer(300)); 
      hm.put("d", new Integer(400)); 

Traversing through the map:

      for (Map.Entry<String, Integer> me : hm.entrySet()) { 
          System.out.print(me.getKey() + ":"); 
          System.out.println(me.getValue()); 
      } 

References:

https://www.geeksforgeeks.org/map-associative-containers-the-c-standard-template-library-stl/

https://www.geeksforgeeks.org/map-interface-java-examples/