Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / C++ Programming Tutorial / Chapter 4: Templates, Exceptions & The STL
CPP ⏱ 12 min read

STL Maps and Sets (std::map, std::set)

Associative containers organize data using keys for instant lookups and sorted, unique collections.

What is it?

• `std::set`: An ordered collection of unique elements (implemented as a self-balancing Red-Black Tree, O(log N) lookup). • `std::map`: An ordered collection of key-value pairs (sorted by key, O(log N) lookup).

Why is it used?

Used for fast lookups, dictionary word mappings, user ID indexing, and duplicate suppression.

Detailed Explanation

Associative Containers: • `std::map<Key, Value>`: Access via `map[key]` or `map.find(key)`. • `std::set<Key>`: Insert via `set.insert(key)`. Elements are always sorted and unique. • `std::unordered_map` / `std::unordered_set`: Hash-table implementations providing O(1) average constant-time lookups.

Syntax Structure

Syntax Blueprint
#include <map>
#include <set>
std::map<std::string, int> course_prices;
course_prices["Python"] = 2500;

Code Example

CPP Code
#include <iostream>
#include <string>
#include <map>
#include <set>

int main() {
    // 1. std::map: Key-Value Course Catalog
    std::map<std::string, int> pricing_map;
    pricing_map["Advanced Python"] = 2500;
    pricing_map["Data Analytics"]  = 2500;
    pricing_map["C & C++ Master"]  = 2500;
    pricing_map["Excel Analytics"] = 1800;
    
    std::cout << "=== Course Price Catalog (std::map) ===\n";
    // Maps are automatically sorted by key!
    for (const auto &[course_name, price] : pricing_map) {
        std::cout << "• " << course_name << ": ₹" << price << "\n";
    }
    
    // 2. std::set: Enrolled student roll numbers (Unique and Sorted)
    std::set<int> enrolled_students = {105, 101, 103, 101, 102, 105}; // Has duplicates!
    
    std::cout << "\n=== Unique Enrolled Students (std::set) ===\n";
    for (const auto &roll : enrolled_students) {
        std::cout << "Roll #" << roll << " ";
    }
    std::cout << "\n";
    
    return 0;
}

Explanation of the Code

• Structured bindings `[course_name, price]` (C++17) unpack key-value pairs directly in the range loop. • `std::set` automatically eliminates duplicate rolls (101, 105) and sorts elements in ascending order.

Expected Output

=== Course Price Catalog (std::map) === • Advanced Python: ₹2500 • C & C++ Master: ₹2500 • Data Analytics: ₹2500 • Excel Analytics: ₹1800 === Unique Enrolled Students (std::set) === Roll #101 Roll #102 Roll #103 Roll #105

Real-World Application

Used for routing tables, symbol tables in compilers, and search engine index maps.

Common Mistakes to Avoid

• Using `map[key]` for read-only lookups (if the key does not exist, `map[key]` will insert an empty default element! Use `.find()` or `.at()` for read-only checking). • Confusing `std::map` (O(log N) tree) with `std::unordered_map` (O(1) hash table).

Quick Practice Challenge

Create a map mapping 3 course codes (e.g. 'PY', 'JS', 'CPP') to their full titles.

Key Takeaways

• `std::map` stores sorted key-value pairs. • `std::set` stores sorted unique elements. • Use structured bindings `for (const auto &[k, v] : map)` in C++17.