#include <vector>
#include <algorithm>
vector<int> nums = {5, 2, 8, 1, 9};
sort(nums.begin(), nums.end());   // 1 2 5 8 9
Need Container
Fast random access, dynamic size vector
Frequent insert/delete in the middle list
Key-value lookup, sorted keys map
Unique elements, sorted set
LIFO access stack
FIFO access queue

Why STL exists

Before STL, every C++ programmer wrote their own linked list, their own sort function, etc. — repetitive and error-prone. STL provides pre-built, well-tested, generic (template-based) versions of the data structures and algorithms used in almost every program.

The three pieces, working together

#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

int main()
{
    vector<int> nums = {5, 2, 8, 1, 9};   // CONTAINER

    sort(nums.begin(), nums.end());       // ALGORITHM, operating via ITERATORS (begin/end)

    for (int n : nums)                    // range-based loop, uses iterators internally
        cout << n << " ";                 // 1 2 5 8 9

    auto it = find(nums.begin(), nums.end(), 8);   // ALGORITHM again
    if (it != nums.end())
        cout << "\nFound 8 at position " << (it - nums.begin());   // position 3

    return 0;
}

map — key-value pairs, worked example

#include <map>
map<string, int> ages;
ages["Ali"] = 25;
ages["Sara"] = 30;
cout << ages["Ali"];   // 25
for (auto& pair : ages)
    cout << pair.first << ": " << pair.second << endl;   // iterates in sorted key order

Why iterators matter — the generalization

An iterator behaves like a pointer (*it dereferences, ++it advances) but works uniformly across very different containers (vector, list, map...). This is why sort(nums.begin(), nums.end()) can work on a vector while the same style of call works on other containers too — the algorithm doesn't need to know the container's internal structure, only how to move an iterator.

Important MCQs

  1. Which STL container provides fast random access and dynamic resizing?
  2. Which STL container stores unique, sorted elements?
  3. STL algorithms like sort() operate generically over containers using:
  4. Which container is best suited for key-value lookups with sorted keys?

Self-Test Questions