Lesson 40 +40 XP

Associative Containers and Container Adaptors: set, map, stack, queue

Associative Containers and Container Adaptors: set, map, stack, queue

Associative containers store elements sorted by a key so that an element can be found quickly by its key rather than by its position. The STL has four: set, multiset, map and multimap. They are usually implemented as balanced binary search trees (red-black trees), so search, insertion and deletion all take O(log n) time. This lesson also covers the three container adaptors, stack, queue and priority_queue, which give a restricted interface on top of a sequence container.

1. set and multiset

A set stores unique values in sorted order (<set>). Inserting a value that is already present has no effect. A multiset is the same but allows duplicates.

MemberTask
insert(x)add x (ignored by set if already present)
erase(x)remove the value x (all copies in a multiset)
find(x)iterator to x, or end() if not found
count(x)how many times x occurs (0 or 1 for a set)
size(), empty(), begin(), end()as for other containers
C++
#include <iostream>
#include <set>
using namespace std;

int main() {
    int data[] = {40, 10, 30, 10, 20, 40, 50};
    set<int> s;
    multiset<int> ms;
    for (int i = 0; i < 7; i++) {
        s.insert(data[i]);
        ms.insert(data[i]);
    }

    cout << "set:      ";
    for (set<int>::iterator it = s.begin(); it != s.end(); ++it) {
        cout << *it << " "; // sorted, no duplicates
    }
    cout << endl;

    cout << "multiset: ";
    for (multiset<int>::iterator it = ms.begin(); it != ms.end(); ++it) {
        cout << *it << " "; // sorted, duplicates kept
    }
    cout << endl;

    cout << "count of 10 in multiset: " << ms.count(10) << endl;

    if (s.find(30) != s.end()) {
        cout << "30 found in set" << endl;
    }
    if (s.find(35) == s.end()) {
        cout << "35 not in set" << endl;
    }

    s.erase(30);
    cout << "after erase(30), size = " << s.size() << endl;
    return 0;
}

Output:

OUTPUT
set:      10 20 30 40 50 
multiset: 10 10 20 30 40 40 50 
count of 10 in multiset: 2
30 found in set
35 not in set
after erase(30), size = 4

Elements of a set cannot be modified through an iterator (that would break the sorted order): erase the old value and insert the new one instead.

2. pair: The Building Block of Maps

A pair (<utility>) holds two values, called first and second. make_pair(a, b) creates one without writing the types.

C++
pair<string, int> p("Delhi", 110001);
cout << p.first << " " << p.second;
p = make_pair("Pune", 411001);

3. map and multimap

A map stores key → value pairs with unique keys, sorted by key (<map>). Each element is a pair<const Key, Value>.

The [] operator looks up a key and returns a reference to its value; if the key is not present, it is inserted with a default value (0 for numbers, empty for strings). A multimap allows duplicate keys and has no [].

MemberTask
m[key]value for key (creates it if missing)
insert(make_pair(k, v))add a pair (ignored if the key exists, in a map)
find(key)iterator to the pair, or end()
count(key)0 or 1 in a map; any number in a multimap
erase(key)remove the pair(s) with that key

Program: a phone directory

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

int main() {
    map<string, string> phone;
    phone["Ravi"] = "9810011111";
    phone["Anu"] = "9810022222";
    phone.insert(make_pair(string("Meera"), string("9810033333")));
    phone["Ravi"] = "9899999999"; // same key: value replaced

    cout << "Directory (" << phone.size() << " entries):" << endl;
    map<string, string>::iterator it;
    for (it = phone.begin(); it != phone.end(); ++it) {
        cout << "  " << it->first << " : " << it->second << endl; // sorted by name
    }

    string name = "Anu";
    it = phone.find(name);
    if (it != phone.end()) {
        cout << name << "'s number is " << it->second << endl;
    }

    if (phone.count("Kabir") == 0) {
        cout << "Kabir is not in the directory" << endl;
    }

    phone.erase("Meera");
    cout << "after erase, size = " << phone.size() << endl;
    return 0;
}

Output:

OUTPUT
Directory (3 entries):
  Anu : 9810022222
  Meera : 9810033333
  Ravi : 9899999999
Anu's number is 9810022222
Kabir is not in the directory
after erase, size = 2

Phone numbers are stored as string: they are identifiers, not quantities, and a 10-digit number does not fit in a 32-bit long.

Program: counting word frequencies

The fact that m[key] creates a missing key with value 0 makes counting very short:

C++
#include <iostream>
#include <map>
#include <string>
#include <sstream>
using namespace std;

int main() {
    string text = "to be or not to be that is the question to ask";
    map<string, int> freq;
    istringstream words(text);
    string w;
    while (words >> w) {
        freq[w]++; // new words start at 0
    }

    for (map<string, int>::iterator it = freq.begin(); it != freq.end(); ++it) {
        if (it->second > 1) {
            cout << it->first << " appears " << it->second << " times" << endl;
        }
    }
    cout << freq.size() << " different words" << endl;
    return 0;
}

Output:

OUTPUT
be appears 2 times
to appears 3 times
9 different words

multimap

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

int main() {
    multimap<string, string> courses; // student -> course, many per student
    courses.insert(make_pair(string("Riya"), string("OOP")));
    courses.insert(make_pair(string("Aman"), string("DBMS")));
    courses.insert(make_pair(string("Riya"), string("DS")));
    courses.insert(make_pair(string("Riya"), string("Maths")));

    cout << "Riya takes " << courses.count("Riya") << " courses:";
    multimap<string, string>::iterator it = courses.find("Riya");
    for (; it != courses.end() && it->first == "Riya"; ++it) {
        cout << " " << it->second;
    }
    cout << endl;
    return 0;
}

Output:

OUTPUT
Riya takes 3 courses: OOP DS Maths

Equal keys are kept together, in insertion order, so walking forward from find() visits all of them.

Associative containers compared

setmultisetmapmultimap
storeskeyskeyskey → value pairskey → value pairs
duplicate keysnoyesnoyes
[] operatornonoyesno
ordersorted by keysorted by keysorted by keysorted by key
search/insert/eraseO(log n)O(log n)O(log n)O(log n)

4. Container Adaptors

A container adaptor is not a new data structure: it wraps an existing sequence container and allows only certain operations. Adaptors have no iterators, so they cannot be used with algorithms or walked with a loop.

AdaptorHeaderBehaviourDefault underlying containerOperations
stack<stack>LIFO (last in, first out)dequepush, pop, top, empty, size
queue<queue>FIFO (first in, first out)dequepush, pop, front, back, empty, size
priority_queue<queue>largest element firstvector (kept as a heap)push, pop, top, empty, size

The underlying container can be changed: stack<int, vector<int> > s;. Note that pop() returns nothing: read the element with top() or front() first.

C++
#include <iostream>
#include <stack>
#include <queue>
#include <vector>
#include <functional>
using namespace std;

int main() {
    stack<int> s;
    queue<int> q;
    priority_queue<int> pq;                                // max at the top
    priority_queue<int, vector<int>, greater<int> > minpq; // min at the top

    int data[] = {30, 10, 50, 20, 40};
    for (int i = 0; i < 5; i++) {
        s.push(data[i]);
        q.push(data[i]);
        pq.push(data[i]);
        minpq.push(data[i]);
    }

    cout << "stack (LIFO):           ";
    while (!s.empty()) {
        cout << s.top() << " ";
        s.pop();
    }
    cout << endl;

    cout << "queue (FIFO):           ";
    while (!q.empty()) {
        cout << q.front() << " ";
        q.pop();
    }
    cout << endl;

    cout << "priority_queue (max):   ";
    while (!pq.empty()) {
        cout << pq.top() << " ";
        pq.pop();
    }
    cout << endl;

    cout << "priority_queue (min):   ";
    while (!minpq.empty()) {
        cout << minpq.top() << " ";
        minpq.pop();
    }
    cout << endl;
    return 0;
}

Output:

OUTPUT
stack (LIFO):           40 20 50 10 30 
queue (FIFO):           30 10 50 20 40 
priority_queue (max):   50 40 30 20 10 
priority_queue (min):   10 20 30 40 50 

Example: checking balanced brackets with a stack

C++
#include <iostream>
#include <stack>
#include <string>
using namespace std;

bool balanced(const string& expr) {
    stack<char> st;
    for (size_t i = 0; i < expr.length(); i++) {
        char c = expr[i];
        if (c == '(' || c == '[' || c == '{') {
            st.push(c);
        } else if (c == ')' || c == ']' || c == '}') {
            if (st.empty()) {
                return false;
            }
            char open = st.top();
            st.pop();
            if ((c == ')' && open != '(') || (c == ']' && open != '[') ||
                (c == '}' && open != '{')) {
                return false;
            }
        }
    }
    return st.empty();
}

int main() {
    string tests[3] = {"{a[b(c)d]e}", "(a+b]", "((x)"};
    for (int i = 0; i < 3; i++) {
        cout << tests[i] << " : " << (balanced(tests[i]) ? "balanced" : "not balanced") << endl;
    }
    return 0;
}

Output:

OUTPUT
{a[b(c)d]e} : balanced
(a+b] : not balanced
((x) : not balanced
💡 Tip

Key points to remember

  • Associative containers keep elements sorted by key in a balanced tree: O(log n) search, insert and erase.
  • set: unique sorted keys; multiset: duplicates allowed.
  • map: unique key → value pairs; m[key] inserts the key if it is missing. multimap: duplicate keys, no [].
  • Map elements are pairs: use it->first (key) and it->second (value).
  • find() returns end() when the key is absent; count() tells how many.
  • Adaptors: stack (LIFO), queue (FIFO), priority_queue (largest first); no iterators; pop() returns nothing.
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. What are associative containers? Explain set and map with programs. (10 Marks)
  • Write: the definition (sorted by key, tree, O(log n)), the set program, the phone directory map program, and the comparison table.
  • Q2. Explain container adaptors. Write a program using stack and queue. (10 Marks)
  • Write: the adaptors table and the stack/queue/priority_queue program with output.
  • Q3. Write a program to count the frequency of each word in a string using a map. (5 Marks)
  • Q4. Differentiate between set and multiset, and between map and multimap. (5 Marks)
  • Q5. What happens when m[key] is used with a key that is not in the map? (2.5 Marks)