Map vs Unordered Map in STL in C++

About Map and Unordered Map

Map and Unordered Map in STL are containers which is used to store elements in key-value pair in the particular order.

map in stl

Map in STL :

Unordered Map in STL :

Important Note

  • The items are stored in mapped way in associative containers called maps.
  • There are key values and mapped values for every element.
  • The key values for any two mapped values cannot be the same.
  • An associated container called unordered map holds elements created by fusing a mapped value with a key value.
  • The element is uniquely identified by the key value, and the mapped value is the content related to the key.

Difference in Map and Unordered Map :

 Map Unordered  Map
Elements are ordered in increasing order Elements are not ordered in the sorted order.
Implementation is done by BST Implementation is done by Hashtable.
It is slow It is fast.
Used when ordering is required Used when no ordering is required.

Example of Map in STL :

Run
#include<iostream>
#include<bits/stdc++.h>
using namespace std;

int main() {
    map< int,int> mpp;
    
    mpp.insert({1,10});
    mpp.insert({2,20});
    mpp.insert({4,40});
    mpp.insert({8,80});
    mpp.insert({6,60});
    mpp.insert({3,30});
    
    cout<<"The key and value in the map : "<< endl;
    for(auto it : mpp){
        cout<< it.first<<" "<< it.second<< endl;
    }
    cout<< endl;
    cout<<"The size of map :"<< mpp.size();
    return 0;
}

Output :

The key and value in the map : 
1 10
2 20
3 30
4 40
6 60
8 80

The size of map :6

In the above program, we take the map insert the key and value in it, when we print them , key will output in the sorted order.

Example of Unordered Map in STL:

Run
#include<iostream>
#include<bits/stdc++.h>
using namespace std;

int main() {
    unordered_map< int,int> mpp;
    
    mpp.insert({1,10});
    mpp.insert({2,20});
    mpp.insert({4,40});
    mpp.insert({8,80});
    mpp.insert({6,60});
    mpp.insert({3,30});
    
    cout<<"The key and value in the map : "<< endl;
    for(auto it : mpp){
        cout<< it.first<<" "<< it.second<< endl;
    }
    cout<< endl;
    cout<<"The size of map :"<< mpp.size();
    return 0;
}

Output :

The key and value in the map : 
3 30
6 60
8 80
4 40
2 20
1 10

The size of map :6

In the above program, we take the map insert the key and value in it, when we print them ,it is not necessary that key will output in the sorted order.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription