Skip to main content

C++ STL Unordered Map – std::unordered_map

In this tutorial you will learn about stl unordered map container i.e. std::unordered_map and all functions applicable on it.

By its name we can say that it comes under Associative containers with Unordered property. We know that any unordered container internally implemented with hash tables. So same has hashing concept in worst case any operation takes O(n) time and in average and best case it takes O(1) time. We can say it vary based on type of hash function we used. With comparison to map containers these work efficiently to find value by using key. And one main difference is that map elements are order but unordered map elements are not in order. Since it is based on key-value pair concept all keys must be unique.

C++ STL Unordered Map – std::unordered_map

Iterators that can be applicable on Unordered map:

begin(): returns iterator to the beginning

end(): returns iterator to the end of the container.

cbegin(): Returns constant iterator to the beginning.

cend(): Returns constant iterator to the end.

To work with unordered map we can separately include unordered_map header file. That is:

#include <unordered_map>

Functions applicable on unordered map:

Inserting and printing:

Here we can insert using index operator []. Main advantage of these key-value type of containers is to store relevant information.

Example:

Andhra – Amaravathi

Telangana – Hyderabad

Odisha – Bhubaneswar

Like this we can store these type of information. Here state names are keys and their capitals are values.

Or we can compare these things with dictionaries in python. For simply understanding and to show all functions on these unordered map  here I am using keys 0, 1, 2, . . . n. And values are user choice. But remember both key and value can be different data types.

Method 1: We can insert using based on key.

Ex: unMap[key] = value;

Method 2: Using insert() function.

Using this we can directly include key and value pair at a time. To say that those are pair, we should use make_pair function.

Since container storing key – value pairs, we use combination of iterators and pointers (“first” for key and “second” for value).

Below example code explains these clearly:

#include <iostream>
#include <unordered_map>

using namespace std;

int main(){
        int value;
        unordered_map <int, int> unMap; // Declearing
        unordered_map <int, int> :: iterator it;
        
        for (int i=0; i<5; i++) {
                cout << "Enter value for key " << i << endl;
                cin >> value;
                unMap [i]= value; // inserting using key 
        }
        
        // inserting using .insert function
        unMap.insert(make_pair(10,100));
        cout << "(Key , Value)" << endl;
        for (it= unMap.begin(); it!= unMap.end(); ++it) {
                cout << "(" << it->first << " , " << it->second << ")" << endl;
        }
        
        return 0;
}

Output

Enter value for key 0
10
Enter value for key 1
20
Enter value for key 2
30
Enter value for key 3
40
Enter value for key 4
50
(Key , Value)
(10 , 100)
(4 , 50)
(0 , 10)
(1 , 20)
(2 , 30)
(3 , 40)

Other modification functions on unordered map:

erase(): We can remove using key. Then key and corresponding value both will be deleted. And by pointing iterator to some pair, we can delete that.

swap(): swaps elements of Unordered map1 to Unordered map2 and vice-versa. Swapping can be done successfully even both containers have different sizes.

clear(): removes all elements in the Unordered map. It results container size to 0.

Example program to show above function:

#include <iostream>
#include <unordered_map>

using namespace std;

int main(){
        unordered_map <int, int> unMap;
        unordered_map <int, int> :: iterator it;
        
        for (int i=0; i<5; i++) {
                unMap [i]= i+10; 
        }
        
        cout << "key - value pairs in unordered map are" << endl;   
        cout << "(Key , Value)" << endl;
        for (it= unMap.begin(); it!= unMap.end(); ++it) {
                cout << "(" << it->first << " , " << it->second << ")" << endl;
        }
        
        cout << "Erasing pair whcih has key value 3" << endl;
        unMap.erase(3);
        it= unMap.begin();
        cout << "Erasing first pair" << endl;
        unMap.erase(it);
        
        cout << "Remaining pairs are" << endl;
        cout << "(Key , Value)" << endl;
        for (it= unMap.begin(); it!= unMap.end(); ++it) {
                cout << "(" << it->first << " , " << it->second << ")" << endl;
        }
        
        // creating new unordered map
        unordered_map <int, int> unMap2;
        for(int i=0; i<5; i++) {
                unMap2[i]= i+100;
        }
        cout << "New unordered map elements are " << endl;
        cout << "(Key , Value)" << endl;
        for (it= unMap2.begin(); it!= unMap2.end(); ++it) {
                cout << "(" << it->first << " , " << it->second << ")" << endl;
        }
        
        cout << "Performing swap operation......." << endl;
        unMap.swap(unMap2);
        cout << "After swap operation second unordered map is " << endl;
        cout << "(Key , Value)" << endl;
        for (it= unMap2.begin(); it!= unMap2.end(); ++it) {
                cout << "(" << it->first << " , " << it->second << ")" << endl;
        }
        
        cout << "After swap operation unMap1 is " << endl;
        cout << "(Key , Value)" << endl;
        for (it= unMap.begin(); it!= unMap.end(); ++it) {
                cout << "(" << it->first << " , " << it->second << ")" << endl;
        }
        
        // clear operation
        cout << "Applying clear operation on unMap2" << endl;
        unMap2.clear();
        
        cout << "Now unMap2 is " << endl;
        cout << "(Key , Value)" << endl;
        for (it= unMap2.begin(); it!= unMap2.end(); ++it) {
                cout << "(" << it->first << " , " << it->second << ")" << endl;
        }
        
        return 0;
}

Output

key – value pairs in unordered map are
(Key , Value)
(4 , 14)
(0 , 10)
(1 , 11)
(2 , 12)
(3 , 13)
Erasing pair whcih has key value 3
Erasing first pair
Remaining pairs are
(Key , Value)
(0 , 10)
(1 , 11)
(2 , 12)
New unordered map elements are
(Key , Value)
(4 , 104)
(0 , 100)
(1 , 101)
(2 , 102)
(3 , 103)
Performing swap operation…….
After swap operation second unordered map is
(Key , Value)
(0 , 10)
(1 , 11)
(2 , 12)
After swap operation unMap1 is
(Key , Value)
(4 , 104)
(0 , 100)
(1 , 101)
(2 , 102)
(3 , 103)
Applying clear operation on unMap2
Now unMap2 is
(Key , Value)

Functions related to capacity:

empty(): returns a Boolean value whether unordered_map is empty or not.

size(): returns present size of the container.

max_size(): returns the maximum size a map can have.

#include<iostream>
#include <unordered_map>

using namespace std;

int main(){
        unordered_map <int, int> unMap;
        unordered_map <int, int> :: iterator it;
        
        for (int i=0; i<5; i++) {
                unMap [i]= i+10; 
        }
        
        cout << "Size of the unordered map is " << unMap.size() << endl;
        cout << "Maximum Size of the unordered map is " << unMap.max_size() << endl;
        
        bool check= unMap.empty();
        if (check)
                cout << "Unordered map is empty" << endl;
        else
                cout << "Unordered map is not empty" << endl;
        
        return 0;
}

Output

Size of the unordered map is 5
Maximum Size of the unordered map is 1152921504606846975
Unordered map is not empty

Comment below if you have any queries related to stl unordered map.

The post C++ STL Unordered Map – std::unordered_map appeared first on The Crazy Programmer.



from The Crazy Programmer https://www.thecrazyprogrammer.com/2017/11/stl-unordered-map.html

Comments

Popular posts from this blog

Rail Fence Cipher Program in C and C++[Encryption & Decryption]

Here you will get rail fence cipher program in C and C++ for encryption and decryption. It is a kind of transposition cipher which is also known as zigzag cipher. Below is an example. Here Key = 3. For encryption we write the message diagonally in zigzag form in a matrix having total rows = key and total columns = message length. Then read the matrix row wise horizontally to get encrypted message. Rail Fence Cipher Program in C #include<stdio.h> #include<string.h> void encryptMsg(char msg[], int key){ int msgLen = strlen(msg), i, j, k = -1, row = 0, col = 0; char railMatrix[key][msgLen]; for(i = 0; i < key; ++i) for(j = 0; j < msgLen; ++j) railMatrix[i][j] = '\n'; for(i = 0; i < msgLen; ++i){ railMatrix[row][col++] = msg[i]; if(row == 0 || row == key-1) k= k * (-1); row = row + k; } printf("\nEncrypted Message: "); for(i = 0; i < key; ++i) f...

Data Encryption Standard (DES) Algorithm

Data Encryption Standard is a symmetric-key algorithm for the encrypting the data. It comes under block cipher algorithm which follows Feistel structure. Here is the block diagram of Data Encryption Standard. Fig1: DES Algorithm Block Diagram [Image Source: Cryptography and Network Security Principles and Practices 4 th Ed by William Stallings] Explanation for above diagram: Each character of plain text converted into binary format. Every time we take 64 bits from that and give as input to DES algorithm, then it processed through 16 rounds and then converted to cipher text. Initial Permutation: 64 bit plain text goes under initial permutation and then given to round 1. Since initial permutation step receiving 64 bits, it contains an 1×64 matrix which contains numbers from 1 to 64 but in shuffled order. After that, we arrange our original 64 bit text in the order mentioned in that matrix. [You can see the matrix in below code] After initial permutation, 64 bit text passed throug...

dotnet sdk list and dotnet sdk latest

Can someone make .NET Core better with a simple global command? Fanie Reynders did and he did it in a simple and elegant way. I'm envious, in fact, because I spec'ed this exact thing out in a meeting a few months ago but I could have just done it like he did and I would have used fewer keystrokes! Last year when .NET Core was just getting started, there was a "DNVM" helper command that you could use to simplify dealing with multiple versions of the .NET SDK on one machine. Later, rather than 'switching global SDK versions,' switching was simplified to be handled on a folder by folder basis. That meant that if you had a project in a folder with no global.json that pinned the SDK version, your project would use the latest installed version. If you liked, you could create a global.json file and pin your project's folder to a specific version. Great, but I would constantly have to google to remember the format for the global.json file, and I'd constan...