C++ Standard Template Library (STL)

The STL provides generic containers, iterators and algorithms — one of C++'s greatest strengths. Instead of writing your own linked list or sort, you use the battle-tested STL versions.

Vector (Dynamic Array)

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

vector<int> nums = {5, 2, 8, 1, 9};

// Adding and removing
nums.push_back(3);      // add to end
nums.pop_back();         // remove from end
nums.insert(nums.begin(), 0); // insert at beginning

// Size
nums.size();             // number of elements
nums.empty();            // true if size is 0

// Accessing
nums[0];                 // first element (no bounds check)
nums.at(0);              // first element (throws if out of bounds)
nums.front();            // first element
nums.back();             // last element

// Sorting
sort(nums.begin(), nums.end());           // ascending
sort(nums.begin(), nums.end(), greater<int>()); // descending

Range-Based For Loop

CPP
vector<string> cities = {"Kathmandu", "Pokhara", "Chitwan"};

for (const auto &city : cities) {  // const & avoids copying
    cout << city << endl;
}

Map (Ordered — Red-Black Tree)

CPP
#include <map>

map<string, int> prices;
prices["Notebook"] = 150;
prices["Pen"] = 25;

cout << prices["Pen"]; // 25

// Iterating with structured binding (C++17)
for (const auto &[key, value] : prices) {
    cout << key << ": " << value << endl;
}

// Safe lookup
if (prices.count("Book")) {
    cout << prices["Book"] << endl;
}

Unordered Map (Hash Table — O(1) lookup)

CPP
#include <unordered_map>

unordered_map<string, int> fast;  // O(1) average lookup
// Same API as map, but unsorted and faster

Set (Unique, Sorted)

CPP
#include <set>

set<string> unique;
unique.insert("apple");
unique.insert("apple");  // duplicate ignored
cout << unique.size();   // 1

unique.count("apple");   // 1 (exists)
unique.count("banana");  // 0 (does not exist)

String

CPP
#include <string>

string s = "Hello, Nepal!";
cout << s.length();        // 13
cout << s.substr(7, 5);    // "Nepal"

s += " 🇳🇵";               // concatenate
s.find("Nepal");           // position (7), or string::npos

// C++17 structured bindings with string
for (char c : s) {
    cout << c << " ";
}

Choosing the Right Container

Container Use when… Lookup Insert
vector<T> Ordered, dynamic size O(1) by index O(1) at end
map<K,V> Sorted key-value pairs O(log n) O(log n)
unordered_map<K,V> Fast key lookup (unsorted) O(1) average O(1) average
set<T> Unique, sorted elements O(log n) O(log n)
list<T> Frequent insert/remove in middle O(n) O(1)

Tips

  • Use vector as your default container — it is the most versatile.
  • Use const auto & in range-for loops to avoid copying.
  • Use unordered_map over map when you do not need sorted order.
  • Prefer STL algorithms (sort, find, count) over hand-written loops.

Next: memory — pointers, smart pointers, and memory management.