CodingMap Container in C++ STL

    Map Container in C++ STL

    As a set, the Map container is also associative and stores elements in an ordered way but Maps store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values.

    Some basic functions associated with Map:

    • begin() – Returns an iterator to the first element in the map.
    • end() – Returns an iterator to the theoretical element that follows last element in the map.
    • size() – Returns the number of elements in the map.
    • empty() – Returns whether the map is empty.
    • insert({keyvalue, mapvalue}) – Adds a new element to the map.
    • erase(iterator position) – Removes the element at the position pointed by the iterator
    • erase(const g)– Removes the key value ‘g’ from the map.
    • clear() – Removes all the elements from the map.

    The Output of the Code would be:

    The map mp is :
    1      40
    2      30
    3      60
    4      20
    5      50
    6      50
    7      10

    In the code above, we have inserted the elements using the insert function and printed the elements using an iterator.

    We have inserted the pairs in an ordered manner of keys, but, if we have not inserted the pairs with keys sorted in any order, we would still get the same output, as a map automatically sorts the pairs according to the value of their keys.

    unordered_map Container in C++ STL:

    The unordered_map is an associated container that stores elements formed by a combination of key value and a mapped value. The key value is used to uniquely identify the element and mapped value is the content associated with the key. Both key and value can be of any type predefined or user-defined.
    Internally unordered_map is implemented using Hash Table, the key provided to map are hashed into indices of a hash table that is why the performance of data structure depends on hash function a lot but on an average, the cost of search, insert and delete from hash table is O(1).

    The Output of the Code above will be:

    The map umap is : 
    E    50
    D    40
    A    10
    B    20
    C    30

    You might have got a different output of the same code, because we have implemented an unordered_map, so there’s no order of the keys to be arranged in any specific order.

    In Java we have different Data Structures such as Hashtable, HashMap, HashSet, LinkedHashMap, LinkedHashSet, TreeSet. LinkedHashMap, TreeSet & LinkedHashSet maintains the objects into a specific order while Hashtable, HashMap & HashSet does not maintain any specific order of objects.



    Please enter your comment!
    Please enter your name here

    Subscribe Today


    Get unlimited access to our EXCLUSIVE Content and our archive of subscriber stories.

    Exclusive content

    Latest article

    More article