Unordered Map and Set

Unordered Map and Unordered Set in C++

IntermediateTopic: STL Containers Programs
Back

C++ Unordered Map and Set Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <string>
using namespace std;

int main() {
    // Unordered Map
    unordered_map<string, int> wordCount;
    
    wordCount["hello"] = 3;
    wordCount["world"] = 2;
    wordCount["c++"] = 5;
    wordCount["programming"] = 1;
    
    cout << "Unordered Map (Hash Map):" << endl;
    for (const auto& pair : wordCount) {
        cout << pair.first << ": " << pair.second << endl;
    }
    
    // Access
    cout << "\nCount of 'c++': " << wordCount["c++"] << endl;
    
    // Check if key exists
    if (wordCount.find("hello") != wordCount.end()) {
        cout << "'hello' found" << endl;
    }
    
    // Unordered Set
    unordered_set<int> numbers;
    
    numbers.insert(5);
    numbers.insert(2);
    numbers.insert(8);
    numbers.insert(1);
    numbers.insert(5);  // Duplicate ignored
    
    cout << "\nUnordered Set (Hash Set): ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;
    
    // Check if element exists
    if (numbers.find(8) != numbers.end()) {
        cout << "Element 8 found" << endl;
    }
    
    // Size
    cout << "Set size: " << numbers.size() << endl;
    
    // Bucket information (hash table details)
    cout << "\nHash table info:" << endl;
    cout << "Number of buckets: " << numbers.bucket_count() << endl;
    cout << "Load factor: " << numbers.load_factor() << endl;
    
    return 0;
}
Output
Unordered Map (Hash Map):
programming: 1
c++: 5
world: 2
hello: 3

Count of 'c++': 5
'hello' found

Unordered Set (Hash Set): 1 8 2 5
Element 8 found
Set size: 4

Hash table info:
Number of buckets: 8
Load factor: 0.5

Understanding Unordered Map and Set

Unordered map and set use hash tables for O(1) average case operations (insert, find, erase). Unlike map/set, they don't maintain sorted order. Unordered containers are faster for lookups but slower for range queries. Use when order doesn't matter and you need fast access. Hash collisions can degrade performance to O(n) worst case.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents