Maps and Sets in C++ STL

Maps and sets are associative containers in C++ STL. Unlike vectors (which use integer indices), these containers organize data using keys and provide very fast lookup, insertion, and deletion.

The set Container

A set stores unique, automatically sorted values. It is like a mathematical set — no duplicate elements are allowed, and the elements are always kept in sorted order.

#include <iostream>
#include <set>
using namespace std;

int main() {
    set<int> s;
    s.insert(30);
    s.insert(10);
    s.insert(20);
    s.insert(10);   // duplicate — ignored

    for (int x : s) {
        cout << x << " ";
    }
    cout << endl;
    return 0;
}

Output:

10 20 30

Common Set Operations

set<int> s = {5, 2, 8, 1, 9};

cout << s.size()  << endl;              // 5
cout << s.count(8) << endl;             // 1 (exists)
cout << s.count(7) << endl;             // 0 (not found)

s.erase(2);                              // remove 2
s.erase(s.find(9));                      // find and remove 9

for (int x : s) cout << x << " ";      // 1 5 8

Checking Membership

set<string> fruits = {"apple", "banana", "cherry"};

if (fruits.find("banana") != fruits.end()) {
    cout << "banana found!" << endl;
} else {
    cout << "Not found." << endl;
}

Output:

banana found!

The map Container

A map stores key-value pairs, sorted by key. Each key is unique, and each key maps to exactly one value. Think of it as a dictionary — you look up a word (key) to find its meaning (value).

#include <iostream>
#include <map>
using namespace std;

int main() {
    map<string, int> phoneBook;
    phoneBook["Alice"] = 9876543210;
    phoneBook["Bob"]   = 9123456789;
    phoneBook["Carol"] = 9988776655;

    cout << "Alice: " << phoneBook["Alice"] << endl;
    cout << "Bob:   " << phoneBook["Bob"]   << endl;
    return 0;
}

Output:

Alice: 9876543210
Bob:   9123456789

Iterating Over a Map

map<string, int> scores = {
    {"Math", 90},
    {"Science", 85},
    {"English", 78}
};

for (auto &pair : scores) {
    cout << pair.first << ": " << pair.second << endl;
}

Output (sorted by key alphabetically):

English: 78
Math: 90
Science: 85

Checking if a Key Exists

map<string, int> ages = {{"Raj", 25}, {"Mia", 30}};

if (ages.find("Raj") != ages.end()) {
    cout << "Raj's age: " << ages["Raj"] << endl;
} else {
    cout << "Raj not found." << endl;
}

Common Map Functions

FunctionDescription
insert({key, val})Insert a key-value pair
erase(key)Remove entry by key
find(key)Returns iterator to key, or end()
count(key)1 if key exists, 0 otherwise
size()Number of key-value pairs
clear()Remove all entries
operator[]Access or create value for key

Word Frequency Counter using Map

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    string words[] = {"apple", "banana", "apple", "cherry", "banana", "apple"};
    map<string, int> freq;

    for (string w : words) {
        freq[w]++;
    }

    for (auto &p : freq) {
        cout << p.first << ": " << p.second << " times" << endl;
    }
    return 0;
}

Output:

apple: 3 times
banana: 2 times
cherry: 1 times

unordered_map and unordered_set

unordered_map and unordered_set use hash tables for O(1) average lookup (faster than the sorted versions but no ordering):

#include <unordered_map>
unordered_map<string, int> fastMap;
fastMap["key1"] = 100;
fastMap["key2"] = 200;

Map vs Set

Featuresetmap
StoresUnique values onlyKey-value pairs
AccessBy valueBy key
SortedYes (ascending)Yes (by key)
Duplicate keysNot allowedNot allowed

Key Takeaways

  • A set stores unique, sorted values — no duplicates.
  • A map stores key-value pairs, sorted by key — keys are unique.
  • Both support fast lookup, insertion, and deletion (O(log n) time).
  • unordered_map and unordered_set provide O(1) average access using hashing.
  • Maps are excellent for building dictionaries, frequency counters, and index tables.

Leave a Comment

Your email address will not be published. Required fields are marked *