std::STL Playground
0 / 41 topics tried
C++ Standard Template Library

Watch vector, map and sort move.

Every container and algorithm on this page runs live in your browser. Click an operation, watch the elements shift, then read the real C++ next to its real output. All code was compiled and run with g++ 13.3 using -std=c++17.

element iterator / touched empty slot or end() error / undefined behavior
vector: one contiguous block, index in O(1)
Playground · write and run your own C++

code editor

compiler GCC 13.3-std=c++17 -O2stdin supportedCtrl + Enter runs

Write any program here and run it. Start from the example below, pick one of the 37 topics from the list, or press Try it on any code block further down the page. Put your program's input in the stdin box, the way you would type it into a terminal.

Open in Compiler Explorer ↗
output
Press ▶ Run to compile.
Where your code runsRun sends your code to Compiler Explorer (godbolt.org), a free public compiler service, and shows what it prints. Don't paste passwords or private code.
  • Compile errors show in red, and the matching lines are marked in the editor.
  • Your draft stays in this browser, so a reload won't lose it. Reset brings back the selected example.
  • Programs are stopped after a few seconds, so an infinite loop shows "timed out" instead of hanging.
Basics · <cmath>

std::pow

#include <cmath>loop O(n)returns double

Raising a number to a power. The loop multiplies result by 2 nine times. pow(2, 9) does the same work but returns a double, so the answer is 512.0 printed as 512.

Doubles can round. A well-known case: some older MinGW builds printed 99 for (int)pow(10, 2). When you need an exact integer, use a loop, or 1LL << n for powers of two.

i=1×2
i=2×2
i=3×2
i=4×2
i=5×2
i=6×2
i=7×2
i=8×2
i=9×2
result = 1binary: 1
// click an operation above to run it
C++ · pow.cpp
void powerFunction() {
    // Value of 2^9, the manual way
    int result = 1;
    for (int i = 1; i <= 9; i++) {
        result *= 2;
    }
    cout << result << endl;

    // Using <cmath>. pow() returns a double.
    cout << pow(2, 9) << endl;

    // Integer-only shortcut for powers of two
    cout << (1 << 9) << endl;
}
Output · g++ 13.3 -std=c++17
512
512
512
  • For large exponents with a modulus (common in contests), write fast exponentiation: square the base and halve the exponent each step. That runs in O(log n) instead of O(n).
  • 1 << 31 overflows a 32-bit int. Use 1LL << 31.
Basics · <utility>

std::pair

#include <utility>access O(1)

A pair stores two values in one variable. The two types can differ: pair<char, int> holds a letter and a number. Read them with .first and .second.

Pairs can nest. In pr4 the first slot is itself a pair, so you reach the 3 with pr4.first.first. Click an expression below to see which slot it reads.

pr1 : pair<int,int>
2
.first
8
.second
pr2 = make_pair(4, 2)
4
.first
2
.second
pr3 : pair<char,int>
'y'
.first
7
.second
pr4 : pair<pair<int,char>,int>
.first (a pair)
3
.first
'a'
.second
9
.second
// click an operation above to run it
C++ · pair.cpp
void pairFunction() {
    // Store 2 values in a single variable
    pair<int, int> pr1 = {2, 8};
    pair<int, int> pr2 = make_pair(4, 2);
    pair<char, int> pr3 = {'y', 7};
    pair<pair<int, char>, int> pr4 = {{3, 'a'}, 9};

    cout << pr1.first << " " << pr1.second << endl;
    cout << pr2.first << " " << pr2.second << endl;
    cout << pr3.first << " " << pr3.second << endl;
    cout << pr4.first.first << " " << pr4.first.second << " " << pr4.second << endl;

    // C++17: unpack a pair into two named variables
    auto [a, b] = pr1;
    cout << a + b << endl;
}
Output · g++ 13.3 -std=c++17
2 8
4 2
y 7
3 a 9
10
  • Pairs compare by .first, then by .second. That is why sort() on a vector of pairs works without a comparator.
  • Pairs are how map stores each entry: it->first is the key, it->second the value.
Basics · <tuple>

std::tuple

#include <tuple>get<i> O(1)i fixed at compile time

A tuple is a pair that can hold any number of values. A student record of roll number, name and grade fits in tuple<int, string, char>. Read a value with get<0>(t), get<1>(t) and so on.

The index inside < > must be a constant. get<i>(t) with a loop variable i does not compile, because each slot can have a different type.

t : tuple<int, string, char>
7
get<0>
"Kundan"
get<1>
'A'
get<2>
// click an operation above to run it
C++ · tuple.cpp
void tupleFunction() {
    // Like pair, but any number of values
    tuple<int, string, char> t = {7, "Kundan", 'A'};
    cout << get<0>(t) << " " << get<1>(t) << " " << get<2>(t) << endl;

    get<0>(t) = 9;                     // get<i> returns a reference
    cout << get<0>(t) << endl;

    auto [roll, name, grade] = t;      // C++17 structured binding
    cout << roll << " " << name << " " << grade << endl;

    int a; string b; char c;
    tie(a, b, c) = t;                  // unpack into existing variables
    cout << a + 1 << endl;

    cout << tuple_size<decltype(t)>::value << endl;   // 3
}
Output · g++ 13.3 -std=c++17
7 Kundan A
9
9 Kundan A
10
3
  • Tuples compare slot by slot, left to right. sort on a vector of tuples sorts by the first value, then the second, then the third.
  • For more than 3 or 4 fields, a small struct with named members reads better than get<3>.
Basics · every container

iterators

begin() / end()rbegin() / rend()*it reads the value

An iterator marks a position inside a container. it is the position, *it is the value stored there. begin() points at the first element. end() points at the slot after the last one, so a loop runs while i != end().

Reverse iterators flip the direction: rbegin() is the last element and rend() sits before the first. Step through both below. Try dereferencing end() to see why it is off limits.

rend
01begin()
12
23
34
end
// click an operation above to run it
C++ · iterators.cpp
void iteratorFunction() {
    vector<int> vec = {1, 2, 3, 4};

    // begin() points at the first element
    vector<int>::iterator beginItr = vec.begin();
    cout << *beginItr << endl;

    // end() is one position AFTER the last element. Never dereference it.
    auto endItr = vec.end();
    for (auto i = beginItr; i != endItr; i++) {   // != works for every container
        cout << *i << " ";
    }
    cout << endl;

    // Range-based for loop (uses iterators behind the scenes)
    for (auto x : vec) cout << x << " ";
    cout << endl;

    // Reverse iterators: rbegin() = last element, rend() = before the first
    for (auto i = vec.rbegin(); i != vec.rend(); i++) {
        cout << *i << " ";
    }
    cout << endl;
}
Output · g++ 13.3 -std=c++17
1
1 2 3 4 
1 2 3 4 
4 3 2 1
Use != in loopsComparing with < only works for random-access iterators (vector, deque, arrays). A list, set or map iterator has no <, and i < ls.end() will not compile. != works everywhere.
Sequence container · dynamic array

std::vector

#include <vector>v[i] O(1)push_back O(1) amortizedinsert/erase front O(n)

A vector is an array that grows. Elements sit side by side in memory, so vec[i] jumps straight to slot i.

The dashed slots are capacity: memory already reserved but not used yet. When size == capacity and you push again, the vector allocates a bigger block and copies every element over. GCC doubles the capacity each time (1, 2, 4, 8, 16), which keeps push_back fast on average. Push until it happens and watch the capacity counter.

size 4capacity 4
01begin()
12
23
34
end()
// click an operation above to run it
C++ · vector.cpp
void vectorFunction() {
    vector<int> vec;              // empty, grows as needed
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);
    vec.emplace_back(4);          // builds the element in place
    cout << vec.size() << endl;

    vector<int> vec1(5);          // 5 zeros
    for (auto i : vec1) cout << i << " ";
    cout << endl;

    vector<int> vec2 = {3, 4, 5, 6};
    vector<int> dupVec(vec2);                         // full copy
    vector<int> dupVec1(vec2.begin() + 1, vec2.end()); // copy of 4 5 6
    for (auto i : dupVec1) cout << i << " ";
    cout << endl;

    vector<int> vec3 = {7, 4, 5, 6, 3, 0};
    cout << vec3.front() << " " << vec3.back() << endl;
    vec3.pop_back();              // removes 0

    vector<int> vec4 = {1, 2, 3, 4, 5, 6};
    vec4.erase(vec4.begin());                      // 2 3 4 5 6
    vec4.erase(vec4.begin() + 1, vec4.end() - 1);  // 2 6
    for (auto i : vec4) cout << i << " ";
    cout << endl;

    vector<int> vec5 = {1, 2, 3};
    cout << vec5[0] << " " << vec5.at(1) << endl;  // at() checks bounds

    vector<int> vec6 = {7, 8}, vec7 = {6, 4};
    swap(vec6, vec7);
    cout << vec6[0] << " " << vec7[0] << endl;

    vector<int> vec8 = {7, 5, 4, 3, 2, 6};
    vec8.insert(vec8.begin(), 1);  // insert(position, value)
    for (auto i : vec8) cout << i << " ";
    cout << endl;

    vec8.clear();                  // size 0, capacity stays
    cout << vec8.size() << endl;
}
Output · g++ 13.3 -std=c++17
4
0 0 0 0 0 
4 5 6 
7 0
2 6 
1 2
6 7
1 7 5 4 3 2 6 
0
  • Know the final size? Call vec.reserve(n) first and skip every reallocation.
  • erase(begin()) shifts every remaining element left. On 1 million elements that is 1 million moves. Remove from the back when you can.
  • clear() sets size to 0 but keeps the capacity. The memory stays reserved.
  • vec.at(10) on a 4-element vector throws std::out_of_range. vec[10] does no check and reads whatever is in memory.
  • A reallocation moves the elements, so any iterator or pointer you saved into the old block is now invalid.
Sequence container · fixed size

std::array

#include <array>arr[i] O(1)size fixed at compile time

array<int, 5> is a plain C array int arr[5] with container manners: it knows its size(), has begin()/end(), supports at() with bounds checking, and can be copied with =.

The size is part of the type, so there is no push_back or erase. Use it when the count never changes: 12 months, 26 letters, 4 directions in a grid.

size 5 (fixed)sizeof 20 bytes
04begin()
18
215
316
423
end()
// click an operation above to run it
C++ · array.cpp
void arrayFunction() {
    // Fixed size, part of the type. Same speed as int arr[5].
    array<int, 5> arr = {4, 8, 15, 16, 23};
    cout << arr.size() << " " << arr.front() << " " << arr.back() << endl;

    arr[2] = 42;
    cout << arr.at(2) << endl;

    arr.fill(0);
    for (int x : arr) cout << x << " ";
    cout << endl;
    // arr.push_back(1);   // does not compile: the size is fixed

    array<int, 3> a = {3, 1, 2};
    sort(a.begin(), a.end());          // works with every algorithm
    for (int x : a) cout << x << " ";
    cout << endl;
}
Output · g++ 13.3 -std=c++17
5 4 23
42
0 0 0 0 0 
1 2 3
  • array<int, 5> a; inside a function leaves the values uninitialised, same as int a[5];. Write array<int, 5> a{}; to get zeros.
Sequence container · doubly linked list

std::list

#include <list>push/pop both ends O(1)insert at iterator O(1)find i-th O(n)

Each element lives in its own node, and each node points to the node before and after it (the ⇄ arrows). Adding at the front only rewires two pointers, which is why list has push_front and vector does not.

The price: there is no ls[3]. To reach the fourth element you walk from the head, one node at a time.

size 5
nullptr
8front()
7
1
2
3back()
nullptr
// click an operation above to run it
C++ · list.cpp
void listFunction() {
    // Doubly linked list: fast insert/remove at both ends
    list<int> ls;
    ls.push_back(1);
    ls.push_back(2);
    ls.push_back(3);
    ls.push_front(7);       // vector has no push_front
    ls.emplace_front(8);

    for (auto it : ls) cout << it << " ";
    cout << endl;

    ls.pop_front();
    ls.pop_back();
    for (auto it : ls) cout << it << " ";
    cout << endl;
}
Output · g++ 13.3 -std=c++17
8 7 1 2 3 
7 1 2
  • In practice a vector is often faster even for middle inserts on small data, because contiguous memory is cache friendly. Reach for list when you insert or splice at iterators you already hold.
  • list has its own ls.sort(). std::sort needs random access and will not compile on a list.
Sequence container · singly linked list

std::forward_list

#include <forward_list>push_front O(1)insert_after O(1)no size()

Each node points only to the next node, so it uses less memory than list. You can only move forward. Because a node can't see the one before it, you insert and erase after a position: insert_after, erase_after.

There is no push_back and no size(). Counting the nodes means walking all of them with distance(fl.begin(), fl.end()).

1begin()
2
3
4
nullptr
// click an operation above to run it
C++ · flist.cpp
void forwardListFunction() {
    // Singly linked: each node knows only the NEXT node
    forward_list<int> fl = {3, 4};
    fl.push_front(2);
    fl.push_front(1);
    for (int x : fl) cout << x << " ";
    cout << endl;

    fl.insert_after(fl.begin(), 9);    // 1 9 2 3 4
    fl.erase_after(fl.begin());        // 1 2 3 4
    fl.pop_front();                    // 2 3 4
    for (int x : fl) cout << x << " ";
    cout << endl;

    // No push_back and no size(). Count the nodes yourself:
    cout << distance(fl.begin(), fl.end()) << endl;
}
Output · g++ 13.3 -std=c++17
1 2 3 4 
2 3 4 
3
  • To insert at the very front with the "after" functions, use fl.before_begin(), a position that sits before the first node.
Sequence container · blocks of arrays

std::deque

#include <deque>push/pop both ends O(1)dq[i] O(1)

A deque (double-ended queue) stores elements in fixed-size blocks plus a small table that tracks the blocks. Pushing to the front fills the first block backwards. When a block is full, the deque adds a new block instead of moving everything.

You get fast pushes at both ends like a list, and dq[i] like a vector. Blocks of 4 below keep it readable; real GCC blocks are 512 bytes.

size 5blocks 2
block 0
[0]1front()
[1]2
block 1
[2]3
[3]4
[4]5back()
block table: [ block 0, block 1 ] first element sits at offset 2 of block 0
// click an operation above to run it
C++ · deque.cpp
void dequeFunction() {
    // Double-ended queue: fast push/pop at both ends AND [] access
    deque<int> dq = {3, 4};
    dq.push_front(2);
    dq.push_front(1);
    dq.push_back(5);

    for (auto x : dq) cout << x << " ";
    cout << endl;

    cout << dq[2] << endl;   // random access works, unlike list
    dq.pop_front();
    dq.pop_back();
    cout << dq.front() << " " << dq.back() << endl;
}
Output · g++ 13.3 -std=c++17
1 2 3 4 5 
3
2 4
Common mix-upvector is one contiguous array. list is linked nodes. deque is a set of array blocks. A deque is not a linked list, and a list is not built on a vector.
Strings & bits · a container of chars

std::string

#include <string>s[i] O(1)find / substr O(n)

A string behaves like a vector<char> with text tools on top. push_back, size, iterators, sort and reverse all work.

Watch the arguments. substr(start, length) takes a length, not an end index, so s.substr(0, 5) gives 5 characters. find returns the index of the first match, or string::npos when there is none.

s "hello"size 5
0h
1e
2l
3l
4o
// click an operation above to run it
C++ · string.cpp
void stringFunction() {
    string s = "hello";
    s.push_back('!');                  // hello!
    s += " world";                     // hello! world
    cout << s << " " << s.size() << endl;

    cout << s.substr(0, 5) << endl;    // substr(start, length)
    cout << s.find("world") << endl;   // index of the first match
    if (s.find("xyz") == string::npos) cout << "npos" << endl;

    s.erase(5, 1);                     // remove 1 char at index 5
    s.insert(0, ">> ");
    cout << s << endl;

    string r = "stl";
    reverse(r.begin(), r.end());
    cout << r << endl;

    int n = stoi("42") + 8;            // string -> int
    cout << to_string(n) + " items" << endl;   // int -> string
}
Output · g++ 13.3 -std=c++17
hello! world 12
hello
7
npos
>> hello world
lts
50 items
npos is not -1 you can compare to intstring::npos is the largest size_t value. Write if (s.find(x) == string::npos). Storing the result in an int and checking < 0 is fragile and warns on most compilers.
Strings & bits · fixed number of bits

std::bitset

#include <bitset>set / test O(1)count O(N/64)

bitset<8> stores 8 on/off flags packed into one byte. Bit 0 is the rightmost when printed. set(i) turns bit i on, reset(i) turns it off, flip(i) toggles it, and count() tells you how many are on.

Click any bit below to flip it and watch the decimal value change.

bit 70
bit 60
bit 50
bit 40
bit 31
bit 21
bit 10
bit 01
b = 00001101to_ulong() = 13count() = 3
// click an operation above to run it
C++ · bitset.cpp
void bitsetFunction() {
    bitset<8> b(13);                   // 13 = 00001101
    cout << b << endl;

    b.set(7);                          // 10001101
    b.reset(0);                        // 10001100
    b.flip(1);                         // 10001110
    cout << b << " = " << b.to_ulong() << endl;

    cout << b.count() << " bits set" << endl;
    cout << b.test(3) << endl;         // is bit 3 on?
    cout << (b << 1) << endl;          // shift left, top bit falls off

    bitset<8> mask("11110000");
    cout << (b & mask) << endl;        // bitwise AND
}
Output · g++ 13.3 -std=c++17
00001101
10001110 = 142
4 bits set
1
00011100
10000000
  • A bitset<1000000> takes 125 KB. A vector<bool> of the same size is similar, a vector<int> takes 4 MB.
  • The size must be a compile-time constant. For a size known only at runtime, use vector<bool>.
Container adapter · LIFO

std::stack

#include <stack>push / pop / top O(1)built on deque

Last in, first out. You only touch the top: push puts an element on top, top() reads it, pop() removes it. There is no iteration and no indexing, so to print a stack you pop it until empty().

The example pushes 5, 8, 6, 3 and prints 3 6 8 5. Run the while loop below to see why the order flips.

size 4empty false
5
8
6
3top()
push and pop happen at the top only.

printed: —
// click an operation above to run it
C++ · stack.cpp
void stackFunction() {
    // LIFO: last in, first out
    stack<int> st;
    st.push(1);
    st.push(2);
    cout << st.size() << endl;
    cout << st.top() << endl;

    st.pop();
    st.pop();
    // st.top() here would be undefined behavior: the stack is empty.
    if (!st.empty()) cout << st.top() << endl;

    stack<int> st1;
    st1.push(5);
    st1.push(8);
    st1.push(6);
    st1.push(3);

    while (!st1.empty()) {
        cout << st1.top() << " ";
        st1.pop();
    }
    cout << endl;
}
Output · g++ 13.3 -std=c++17
2
2
3 6 8 5
Undefined behaviorCalling top() or pop() on an empty stack is not a guaranteed runtime error. It may crash, print garbage, or appear to work and break later. Check !st.empty() first. The button above shows what would happen.
  • Real uses: undo history, matching brackets in "(a[b]{c})", depth-first search without recursion.
Container adapter · FIFO

std::queue

#include <queue>push / pop / front / back O(1)

First in, first out, like a line at a ticket counter. push joins at the back, pop leaves from the front. front() and back() read the two ends.

size 5
◀ pop() leaves here
32front()
43
45
54
72back()
◀ push() joins here
printed: —
// click an operation above to run it
C++ · queue.cpp
void queueFunction() {
    // FIFO: first in, first out
    queue<int> q;
    q.push(32);
    q.push(43);
    q.push(45);
    q.push(54);
    q.push(72);

    cout << q.front() << " " << q.back() << endl;

    while (!q.empty()) {
        cout << q.front() << " ";
        q.pop();
    }
    cout << endl;
}
Output · g++ 13.3 -std=c++17
32 72
32 43 45 54 72
  • Breadth-first search uses a queue: visit a node, push its neighbours, pop the next node. The shortest path in an unweighted grid falls out of that order.
Container adapter · binary heap

std::priority_queue

#include <queue>top O(1)push / pop O(log n)

A priority_queue is a binary heap stored inside a vector. Index i has children at 2i+1 and 2i+2. In a max-heap every parent is at least as large as its children, so the maximum always sits at index 0.

push adds the value at the end and swaps it upward while it beats its parent. pop moves the last element to the root and swaps it downward. Each move climbs one level, and a heap of n elements has about log₂ n levels. With 1,000,000 elements that is 20 swaps at most.

type max-heapsize 5top 10
010
18
25
32
46
010top()
18
25
32
46
↑ the same heap as it sits in the vector: children of index i are 2i+1 and 2i+2
// click an operation above to run it
C++ · pq.cpp
void priorityQueuePQ() {
    // Max-heap by default: the largest element sits on top
    priority_queue<int> pq;
    pq.push(5);
    pq.push(2);
    pq.push(10);
    pq.push(8);
    pq.push(6);

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

    // Min-heap: smallest element on top
    priority_queue<int, vector<int>, greater<int>> spq;
    for (int x : {5, 2, 10, 8, 6}) spq.push(x);

    while (!spq.empty()) {
        cout << spq.top() << " ";
        spq.pop();
    }
    cout << endl;
}
Output · g++ 13.3 -std=c++17
10
10 8 6 5 2 
2 5 6 8 10
  • greater<int> flips the order and makes a min-heap. You must also pass the underlying container, hence priority_queue<int, vector<int>, greater<int>>.
  • Dijkstra's shortest path uses a min-heap of pair<dist, node>.
Ordered associative · red-black tree

std::set

#include <set>insert / erase / find O(log n)unique + sorted

A set keeps unique values in ascending order. Insert 12 twice and the second insert is ignored. Internally it is a balanced binary tree, so each operation walks one path from root to leaf: about 20 steps for a million elements.

lower_bound(x) returns the first element ≥ x. upper_bound(x) returns the first element > x. If nothing qualifies you get end(). Try 11, 12 and 214 below.

size 5
2
12
21
211
213
end
// click an operation above to run it
C++ · set.cpp
void setDS() {
    // Unique elements, always sorted ascending
    set<int> st;
    st.insert(12);
    st.insert(8);
    st.insert(21);
    st.insert(12);          // duplicate, ignored
    for (auto i : st) cout << i << " ";
    cout << endl;

    auto it = st.find(12);  // returns st.end() when missing
    if (it != st.end()) cout << *it << endl;

    cout << st.count(21) << endl;   // 1 if present, else 0

    st.erase(12);
    for (auto i : st) cout << i << " ";
    cout << endl;

    set<int> st3 = {2, 21, 12, 211, 213};
    auto it1 = next(st3.begin());   // points at 12
    auto it2 = prev(st3.end());     // points at 213
    st3.erase(it1, it2);            // removes 12 21 211
    for (auto x : st3) cout << x << " ";
    cout << endl;

    set<int> st4 = {2, 21, 12, 211, 213};
    auto lb = st4.lower_bound(11);  // first element >= 11
    if (lb != st4.end()) cout << *lb << endl;

    auto ub = st4.upper_bound(214); // first element > 214
    if (ub == st4.end()) cout << "Pointing to end" << endl;
    else cout << *ub << endl;       // check BEFORE dereferencing
}
Output · g++ 13.3 -std=c++17
8 12 21 
12
1
8 21 
2 213 
12
Pointing to end
Check before *upper_bound(214) on this set returns end(). Printing *ub before checking ub == st.end() reads past the tree: undefined behavior. The fixed code checks first.
  • Use the member st.lower_bound(x), not std::lower_bound(st.begin(), st.end(), x). The free function is O(n) on a set because set iterators can't jump.
  • erase(it1, it2) removes the half-open range: it1 is removed, it2 is kept.
Ordered associative · duplicates allowed

std::multiset

#include <set>insert / find O(log n)count O(log n + k)

Same as set, but duplicates stay. Values are still sorted, and equal values sit next to each other.

The trap is erase. ms.erase(2) with a value removes every 2. ms.erase(ms.find(2)) with an iterator removes one. Try both.

size 9
1
1
1
2
2
3
3
3
3
end
// click an operation above to run it
C++ · multiset.cpp
void multisetDS() {
    // Like set, but keeps duplicates. Still sorted.
    multiset<int> ms = {1, 1, 1, 2, 2, 3, 3, 3, 3};
    for (auto x : ms) cout << x << " ";
    cout << endl;

    cout << *ms.find(1) << endl;    // iterator to the first 1

    auto removed = ms.erase(1);     // erase(value) removes ALL copies
    cout << removed << " removed" << endl;

    ms.erase(ms.find(2));           // erase(iterator) removes ONE copy
    for (auto x : ms) cout << x << " ";
    cout << endl;

    cout << ms.count(3) << endl;
}
Output · g++ 13.3 -std=c++17
1 1 1 2 2 3 3 3 3 
1
3 removed
2 3 3 3 3 
4
  • A multiset works as a sorted bag for "sliding window median" or "remove one copy of the largest" problems: ms.erase(prev(ms.end())).
Ordered associative · key → value

std::map

#include <map>[] / insert / find O(log n)sorted by key

A map stores key-value pairs with unique keys, sorted by key. It is the same tree as a set, with a value attached to each key.

Three behaviors catch people out, and all three are buttons below. mpp[k] = v overwrites an existing value. mpp.insert({k, v}) does not overwrite when the key exists. Reading mpp[k] for a missing key creates it with an empty value.

size 4
1→Yaswanth
2→Kundan
3→Varsha
4→Raja
end()
// click an operation above to run it
C++ · map.cpp
void mapDS() {
    // key -> value, sorted by key, O(log n) operations
    map<int, string> mpp;
    mpp[1] = "Yaswanth";
    mpp[2] = "Kundan";
    mpp[3] = "Varsha";
    mpp[3] = "Vandana";            // [] overwrites
    mpp.insert({4, "Raja"});
    mpp.insert({4, "Ravi"});       // insert does NOT overwrite

    for (auto it : mpp) cout << it.first << " -> " << it.second << endl;

    auto it = mpp.find(5);
    if (it == mpp.end()) cout << "Pointing to end" << endl;
    else cout << it->first << " -> " << it->second << endl;

    cout << mpp.size() << endl;
    cout << "[" << mpp[9] << "]" << endl;  // reading a missing key CREATES it
    cout << mpp.size() << endl;
}
Output · g++ 13.3 -std=c++17
1 -> Yaswanth
2 -> Kundan
3 -> Vandana
4 -> Raja
Pointing to end
4
[]
5
  • To check for a key without creating it, use mpp.count(k), mpp.find(k) != mpp.end(), or mpp.contains(k) in C++20.
  • Counting words: freq[word]++ works because a missing key starts at 0.
Ordered associative · duplicate keys

std::multimap

#include <map>insert O(log n)equal_range O(log n)no [] operator

A multimap allows the same key many times. Entries are sorted by key only. Entries with equal keys keep the order you inserted them, which is why the output shows 1 -> a, 1 -> b, 1 -> a.

equal_range(k) returns a pair of iterators. first points at the first entry with key k. second points one past the last one. Loop from first while i != second.

size 7
1→a
1→b
1→a
2→a
2→a
2→b
3→b
end()
// click an operation above to run it
C++ · multimap.cpp
void multiMapDS() {
    // Duplicate keys allowed, sorted by key
    multimap<int, char> mpp;
    mpp.insert({3, 'b'});
    mpp.insert({1, 'a'});
    mpp.insert({1, 'b'});
    mpp.insert({1, 'a'});
    mpp.insert({2, 'a'});
    mpp.insert({2, 'a'});
    mpp.insert({2, 'b'});

    for (auto it : mpp) cout << it.first << " -> " << it.second << endl;
    cout << endl;

    // first  -> first element with key 2
    // second -> one position after the last element with key 2
    auto range = mpp.equal_range(2);
    for (auto i = range.first; i != range.second; i++) {
        cout << i->first << " -> " << i->second << endl;
    }
}
Output · g++ 13.3 -std=c++17
1 -> a
1 -> b
1 -> a
2 -> a
2 -> a
2 -> b
3 -> b

2 -> a
2 -> a
2 -> b
  • A multimap has no []: with several values per key, mm[2] would be ambiguous.
Unordered associative · hash table

std::unordered_set

#include <unordered_set>insert / find O(1) averageworst O(n)

Values go into buckets. A hash function turns the value into a bucket number, so a lookup computes one number and checks only that bucket. No tree to walk, which makes the average cost O(1).

This model uses x % 7 so you can predict where each value lands. GCC hashes an int to itself and then takes value % bucket_count, so the idea matches. Because buckets follow the hash, iteration order looks random, and there is no lower_bound.

size 5buckets 7load factor 0.71
bucket 0
7
bucket 1
1
8
bucket 2
2
bucket 3
empty
bucket 4
4
bucket 5
empty
bucket 6
empty
// click an operation above to run it
C++ · uset.cpp
void unorderedSet() {
    // Unique elements, stored in hash buckets (no order)
    unordered_set<int> st;
    st.insert(1);
    st.insert(4);
    st.insert(2);
    st.insert(8);
    st.insert(7);

    // Order depends on the hash table, not on the values
    for (auto it : st) cout << it << " ";
    cout << endl;

    cout << st.count(8) << " " << st.count(9) << endl;
    // No lower_bound / upper_bound: nothing is sorted
}
Output · g++ 13.3 -std=c++17
7 8 2 4 1 
1 0
  • Worst case: when many values land in one bucket, lookups scan a long chain. Try inserting 7, 14, 21, 28 to see a single bucket fill up.
  • Iteration order differs between compilers. Never rely on it.
  • unordered_multiset and unordered_multimap exist too: same buckets, duplicates allowed.
Unordered associative · hash table

std::unordered_map

#include <unordered_map>[] / find O(1) averageworst O(n)

A map built on a hash table. The key decides the bucket, the value rides along. You get the same [], insert, find and count as map, faster on average, with no ordering. This model hashes the key with key % 5.

The output of the example came out as 4, 3, 2, 1 on g++ 13.3. Another compiler can print a different order.

size 4buckets 5load factor 0.80
bucket 0
empty
bucket 1
1→Yaswanth
bucket 2
2→Kundan
bucket 3
3→Varsha
bucket 4
4→Raja
// click an operation above to run it
C++ · umap.cpp
void unorderedMap() {
    // Average O(1) per operation, no ordering
    unordered_map<int, string> mpp;
    mpp[1] = "Yaswanth";
    mpp[2] = "Kundan";
    mpp[3] = "Varsha";
    mpp.insert({4, "Raja"});

    for (auto it : mpp) cout << it.first << " -> " << it.second << endl;
    cout << mpp.count(3) << endl;
}
Output · g++ 13.3 -std=c++17
4 -> Raja
3 -> Varsha
2 -> Kundan
1 -> Yaswanth
1
  • Use map when you need keys in order or range queries. Use unordered_map for plain lookups like frequency counts. pair keys don't have a default hash, so unordered_map<pair<int,int>, int> needs a custom hash.
Algorithm · <algorithm>

std::sort

#include <algorithm>O(n log n)range is [first, last)

sort(first, last) sorts the half-open range: first is included, last is not. So sort(nums + 1, nums + 4) sorts indices 1, 2 and 3 and leaves 0 and 4 alone. The result is 9 1 3 4 0.

For an array, nums + k is a pointer to index k. For a vector, use vec.begin() + k. Same idea.

09
14
21
33
40
bar height = value. Indices on top.
// click an operation above to run it
C++ · sort.cpp
void sorting() {
    int nums[5] = {9, 4, 1, 3, 0};
    sort(nums + 1, nums + 4);   // sorts indices 1, 2, 3 only
    for (auto i : nums) cout << i << " ";
    cout << endl;

    vector<int> vec = {5, 7, 8, 8, 1};
    sort(vec.begin(), vec.end());
    for (auto it : vec) cout << it << " ";
    cout << endl;

    sort(vec.begin(), vec.end(), greater<int>());  // descending
    for (auto it : vec) cout << it << " ";
    cout << endl;
}
Output · g++ 13.3 -std=c++17
9 1 3 4 0 
1 5 7 8 8 
8 8 7 5 1
  • GCC's std::sort is introsort: quicksort that switches to heapsort if recursion gets too deep, and insertion sort for small pieces. It is not stable. Use stable_sort when equal elements must keep their order.
Sorting · keeps ties in order

std::stable_sort

#include <algorithm>O(n log n)extra memory O(n)

Two students both scored 90. A stable sort promises that whoever came first in the input still comes first in the output. std::sort makes no such promise and may swap them.

This matters when you sort twice: sort by name first, then stable_sort by marks, and students with equal marks stay alphabetical.

input #090Asha
input #175Bala
input #290Chetan
input #375Divya
// click an operation above to run it
C++ · stable.cpp
void stableSortFunction() {
    // (marks, name), listed alphabetically
    vector<pair<int, string>> st = {
        {90, "Asha"}, {75, "Bala"}, {90, "Chetan"}, {75, "Divya"}};

    stable_sort(st.begin(), st.end(), [](auto &a, auto &b) {
        return a.first > b.first;      // compare marks only
    });
    for (auto &[marks, name] : st) cout << marks << " " << name << endl;
    // Ties keep their input order: Asha before Chetan, Bala before Divya
}
Output · g++ 13.3 -std=c++17
90 Asha
90 Chetan
75 Bala
75 Divya
Sorting · sort only what you need

std::nth_element & partial_sort

#include <algorithm>nth_element O(n) avgpartial_sort O(n log k)

nth_element(first, first + k, last) puts the value that belongs at index k into index k. Everything left of it is ≤, everything right is ≥, and neither side is sorted. That is enough for a median or the k-th smallest score, and it runs in linear time.

partial_sort(first, first + k, last) sorts only the first k positions. Use it for "top 3 scores" when fully sorting 1,000,000 values would waste time.

09
12
27
34
45
51
68
// click an operation above to run it
C++ · nth.cpp
void nthAndPartial() {
    vector<int> v = {9, 2, 7, 4, 5, 1, 8};
    // Put the element that belongs at index 2 in place. O(n) average.
    nth_element(v.begin(), v.begin() + 2, v.end());
    cout << v[2] << endl;              // 4, the 3rd smallest
    // Left of index 2: all <= 4. Right: all >= 4. Neither side is sorted.

    vector<int> w = {9, 2, 7, 4, 5, 1, 8};
    partial_sort(w.begin(), w.begin() + 3, w.end());   // smallest 3, sorted
    for (int i = 0; i < 3; i++) cout << w[i] << " ";
    cout << endl;

    vector<int> m = {5, 3, 8, 1, 9};
    nth_element(m.begin(), m.begin() + m.size() / 2, m.end());
    cout << "median " << m[m.size() / 2] << endl;
}
Output · g++ 13.3 -std=c++17
4
1 2 4 
median 5
Custom ordering · sort(first, last, comp)

comparators

comp(a, b) → true means a goes firstmust be strict

A comparator answers one question: should a come before b? sort calls it many times and arranges elements from the answers.

complexComparator sorts pairs by second descending, and breaks ties by first ascending. Click any two pairs below to ask the comparator about them, then sort.

0{1, 6}
1{1, 5}
2{2, 6}
3{2, 9}
4{3, 9}
Click two pairs to ask the comparator which goes first.
// click an operation above to run it
C++ · comparator.cpp
// Return true when ele1 must come BEFORE ele2.
// Must be strict: equal elements return false.
bool internalComparator(int ele1, int ele2) {
    return ele1 > ele2;          // descending order
}

bool complexComparator(pair<int, int> a, pair<int, int> b) {
    if (a.second > b.second) return true;   // bigger second first
    if (a.second < b.second) return false;
    return a.first < b.first;               // tie: smaller first first
}

void comparatorDemo() {
    int nums[4] = {5, 6, 1, 2};
    sort(nums, nums + 4, internalComparator);
    for (int i = 0; i < 4; i++) cout << nums[i] << " ";
    cout << endl;

    pair<int, int> ps[5] = {{1, 6}, {1, 5}, {2, 6}, {2, 9}, {3, 9}};
    sort(ps, ps + 5, complexComparator);
    for (auto &p : ps) cout << p.first << " -> " << p.second << endl;
}
Output · g++ 13.3 -std=c++17
6 5 2 1 
2 -> 9
3 -> 9
1 -> 6
2 -> 6
1 -> 5
Never return true for equal elementsA comparator written as if (a < b) return false; else return true; returns true when a == b. That breaks the rule sort relies on (comp(a, a) must be false). With enough duplicates, std::sort can run past the end of the array and crash. Write return a > b; instead.
Algorithm · linear scan

std::count & find

#include <algorithm>O(n)

Both walk the range from left to right. count checks every element and returns how many match. find stops at the first match and returns an iterator to it. When nothing matches, find returns last (here nums + 5), so compare against that before using *it.

06
12
21
31
40
5nums+5
// click an operation above to run it
C++ · countfind.cpp
void countAndFind() {
    int nums[5] = {6, 2, 1, 1, 0};

    cout << count(nums, nums + 5, 1) << endl;  // 1 appears 2 times

    // find returns an iterator to the FIRST match, or the end pointer
    auto it = find(nums, nums + 5, 7);
    if (it == nums + 5) cout << "Not Found" << endl;
    else cout << *it << endl;

    auto it2 = find(nums, nums + 5, 1);
    cout << "found at index " << (it2 - nums) << endl;
}
Output · g++ 13.3 -std=c++17
2
Not Found
found at index 2
  • On a set or map, call the member st.find(x). It is O(log n). std::find on a set still scans every element.
Searching · sorted ranges

std::binary_search

#include <algorithm>O(log n)range must be sorted

Binary search looks at the middle, throws away the half that can't contain the answer, and repeats. 1,000,000 elements need at most 20 looks.

binary_search only answers yes or no. lower_bound (first ≥ x) and upper_bound (first > x) return positions, and ub - lb counts how many times x appears. Step through the search below and watch lo, mid and hi close in.

01
13
23
33
47
59
612
7end
// click an operation above to run it
C++ · bsearch.cpp
void binarySearchFunction() {
    // Only on SORTED ranges. O(log n).
    vector<int> v = {1, 3, 3, 3, 7, 9, 12};
    cout << binary_search(v.begin(), v.end(), 7) << endl;   // 1
    cout << binary_search(v.begin(), v.end(), 5) << endl;   // 0

    auto lb = lower_bound(v.begin(), v.end(), 3);   // first >= 3
    auto ub = upper_bound(v.begin(), v.end(), 3);   // first > 3
    cout << (lb - v.begin()) << " " << (ub - v.begin()) << endl;
    cout << "3 appears " << (ub - lb) << " times" << endl;

    auto it = lower_bound(v.begin(), v.end(), 10);
    if (it != v.end()) cout << *it << endl;         // smallest value >= 10
}
Output · g++ 13.3 -std=c++17
1
0
1 4
3 appears 3 times
12
Unsorted inputOn an unsorted vector these functions still run and return something. The answer is just wrong. Sort first, or keep the data in a set.
Searching · with a condition

count_if, find_if, all_of, any_of, none_of

#include <algorithm>O(n)takes a lambda

These take a condition instead of a value. You write the condition as a lambda: [](int x) { return x % 2 == 0; } is a small unnamed function that returns true for even numbers.

all_of, any_of and none_of stop as soon as the answer is known. Pick a condition and run each one to see how many elements it actually checks.

lambda:
04
17
210
33
48
end
// click an operation above to run it
C++ · pred.cpp
void predicateFunctions() {
    vector<int> v = {4, 7, 10, 3, 8};
    auto isEven = [](int x) { return x % 2 == 0; };   // a lambda

    cout << count_if(v.begin(), v.end(), isEven) << endl;              // 3

    auto it = find_if(v.begin(), v.end(), [](int x) { return x > 8; });
    if (it != v.end()) cout << *it << endl;                            // 10

    cout << all_of(v.begin(), v.end(), [](int x) { return x > 0; }) << endl;   // 1
    cout << any_of(v.begin(), v.end(), [](int x) { return x > 9; }) << endl;   // 1
    cout << none_of(v.begin(), v.end(), isEven) << endl;                       // 0
}
Output · g++ 13.3 -std=c++17
3
10
1
1
0
  • all_of on an empty range returns true, any_of returns false. There is nothing to break the rule, and nothing to satisfy it.
Algorithm · <algorithm>

std::max_element & reverse

#include <algorithm>O(n)

max_element and min_element return an iterator, not a value. Use *it for the value and it - nums for the index. reverse swaps elements from both ends toward the middle.

07
16
24
310
49
// click an operation above to run it
C++ · minmax.cpp
void maxMinAndReverse() {
    int nums[5] = {7, 6, 4, 10, 9};

    auto it = max_element(nums, nums + 5);   // iterator, so use *
    cout << *it << " at index " << (it - nums) << endl;
    auto it1 = min_element(nums, nums + 5);
    cout << *it1 << " at index " << (it1 - nums) << endl;

    reverse(nums, nums + 5);
    for (auto i : nums) cout << i << " ";
    cout << endl;

    // max / min of a list of values (initializer list)
    cout << max({3, 9, 4}) << " " << min({3, 9, 4}) << endl;

    // both at once, one pass
    auto [lo, hi] = minmax_element(nums, nums + 5);
    cout << *lo << " " << *hi << endl;
}
Output · g++ 13.3 -std=c++17
10 at index 3
4 at index 2
9 10 4 6 7 
9 3
4 10
  • Need both at once? minmax_element returns a pair of iterators in a single pass.
  • For a handful of plain values, max({3, 9, 4}) takes an initializer list and returns 9. No array needed.
Modifying · shift with wrap-around

std::rotate

#include <algorithm>O(n)

rotate(first, middle, last) moves middle to the front and wraps the earlier elements to the back. rotate(v.begin(), v.begin() + 2, v.end()) turns 1 2 3 4 5 6 into 3 4 5 6 1 2: a left rotation by 2.

For a right rotation, use reverse iterators: rotate(v.rbegin(), v.rbegin() + k, v.rend()).

01
12
23
34
45
56
// click an operation above to run it
C++ · rotate.cpp
void rotateFunction() {
    vector<int> v = {1, 2, 3, 4, 5, 6};
    // rotate(first, middle, last): middle becomes the new first
    rotate(v.begin(), v.begin() + 2, v.end());      // left by 2
    for (int x : v) cout << x << " ";
    cout << endl;

    rotate(v.rbegin(), v.rbegin() + 1, v.rend());   // right by 1
    for (int x : v) cout << x << " ";
    cout << endl;
}
Output · g++ 13.3 -std=c++17
3 4 5 6 1 2 
2 3 4 5 6 1
  • If k can be larger than the size, use k % v.size() first. v.begin() + 8 on 6 elements is out of range.
Modifying · remove adjacent duplicates

std::unique

#include <algorithm>O(n)does not change size

unique slides each new value forward over the repeats and returns an iterator to the new logical end. It does not shrink the vector. The leftover tail still exists with unspecified values until you erase it.

It also only compares neighbours, so sort first. The full idiom is sort, then v.erase(unique(v.begin(), v.end()), v.end()).

size 6
03
11
23
32
41
53
end
// click an operation above to run it
C++ · unique.cpp
void uniqueFunction() {
    vector<int> v = {3, 1, 3, 2, 1, 3};
    sort(v.begin(), v.end());                   // 1 1 2 3 3 3
    auto newEnd = unique(v.begin(), v.end());   // 1 2 3 ? ? ?
    cout << (newEnd - v.begin()) << " unique" << endl;
    v.erase(newEnd, v.end());                   // drop the leftover tail
    for (int x : v) cout << x << " ";
    cout << endl;

    // unique only removes ADJACENT duplicates
    vector<int> w = {1, 2, 1, 1};
    w.erase(unique(w.begin(), w.end()), w.end());
    for (int x : w) cout << x << " ";
    cout << endl;
}
Output · g++ 13.3 -std=c++17
3 unique
1 2 3 
1 2 1
Modifying · set many values at once

std::fill & iota

#include <algorithm>#include <numeric>O(n)

fill(first, last, value) writes the same value into every slot of the range. It is the standard way to reset a DP table to -1.

iota(first, last, start) writes start, start + 1, start + 2 and so on. Use it to build the index list 0 1 2 … n-1 that you then sort by some key.

00
10
20
30
40
50
// click an operation above to run it
C++ · filliota.cpp
void fillAndIota() {
    vector<int> v(6);
    fill(v.begin(), v.end(), 7);             // 7 7 7 7 7 7
    for (int x : v) cout << x << " ";
    cout << endl;

    iota(v.begin(), v.end(), 1);             // 1 2 3 4 5 6  (<numeric>)
    for (int x : v) cout << x << " ";
    cout << endl;

    fill(v.begin() + 2, v.begin() + 4, 0);   // indices 2 and 3
    for (int x : v) cout << x << " ";
    cout << endl;

    int dp[5];
    fill(dp, dp + 5, -1);                    // common DP setup
    cout << dp[0] << " " << dp[4] << endl;
}
Output · g++ 13.3 -std=c++17
7 7 7 7 7 7 
1 2 3 4 5 6 
1 2 0 0 5 6 
-1 -1
  • memset(dp, -1, sizeof dp) works for -1 and 0 only, because it sets bytes. fill works for any value.
Modifying · apply a function to every element

std::transform & for_each

#include <algorithm>O(n)

transform reads each input element, calls your function, and writes the result to an output range. The output can be a different vector or the same one.

for_each just calls your function on each element. To change the elements, the lambda must take a reference: [](int &x) { x *= 10; }. Without the & it changes a copy and the vector stays the same.

v
01
12
23
34
out
0
1
2
3
// click an operation above to run it
C++ · transform.cpp
void transformFunction() {
    vector<int> v = {1, 2, 3, 4};
    vector<int> sq(v.size());
    transform(v.begin(), v.end(), sq.begin(), [](int x) { return x * x; });
    for (int x : sq) cout << x << " ";
    cout << endl;

    // & in the lambda means "change the element in place"
    for_each(v.begin(), v.end(), [](int &x) { x *= 10; });
    for (int x : v) cout << x << " ";
    cout << endl;

    string s = "Hello STL";
    transform(s.begin(), s.end(), s.begin(), ::toupper);
    cout << s << endl;
}
Output · g++ 13.3 -std=c++17
1 4 9 16 
10 20 30 40 
HELLO STL
  • The output range must already have room. vector<int> sq(v.size()) makes that room; an empty vector plus back_inserter(sq) also works.
Algorithm · lexicographic order

std::next_permutation

#include <algorithm>one step O(n)all n! orders

next_permutation rearranges the range into the next larger order, the way words follow each other in a dictionary. It returns false after the largest order (cba) and resets the range to the smallest (abc). That is why the do { } while loop prints each permutation once.

Start sorted or you miss some: starting from bca prints only bca cab cba. prev_permutation walks backwards, so start it from descending order.

0a
1b
2c
abc
// click an operation above to run it
C++ · perm.cpp
void permutations() {
    // Start from sorted order to get ALL permutations
    string str = "abc";
    do {
        cout << str << " ";
    } while (next_permutation(str.begin(), str.end()));
    cout << endl;

    // Only permute the first two characters
    string str1 = "abc";
    do {
        cout << str1 << " ";
    } while (next_permutation(str1.begin(), str1.end() - 1));
    cout << endl;

    // prev_permutation walks backwards, so start from descending order
    string str2 = "cba";
    do {
        cout << str2 << " ";
    } while (prev_permutation(str2.begin(), str2.end()));
    cout << endl;
}
Output · g++ 13.3 -std=c++17
abc acb bac bca cab cba 
abc bac 
cba cab bca bac acb abc
  • 3 letters give 6 orders. 10 letters give 3,628,800. Brute force over permutations only works for small n, around 10 or less.
Algorithm · <numeric>

std::accumulate

#include <numeric>O(n)

accumulate(first, last, init) starts at init and adds each element. With init 0 you get the plain sum, 16. With init 5 you get 21.

The type of init sets the type of the running total. Summing a vector<long long> with init 0 adds into an int and can overflow. Write 0LL.

06
12
21
37
40
total = 0
// click an operation above to run it
C++ · accumulate.cpp
void accumulateDemo() {   // renamed: don't reuse the std name
    int nums[5] = {6, 2, 1, 7, 0};
    cout << accumulate(nums, nums + 5, 0) << endl;  // 0 + sum
    cout << accumulate(nums, nums + 5, 1) << endl;  // 1 + sum
    cout << accumulate(nums, nums + 5, 5) << endl;  // 5 + sum
}
Output · g++ 13.3 -std=c++17
16
17
21
Name clashNaming your own function accumulate() while using namespace std; is active compiles here, but it is fragile and confusing to read. The snippet renames it to accumulateDemo.
Numeric · prefix sums

std::partial_sum

#include <numeric>build O(n)range sum query O(1)

partial_sum writes running totals: pre[i] = v[0] + … + v[i]. After that, the sum of any range v[l..r] is pre[r] - pre[l - 1], one subtraction instead of a loop.

With 100,000 queries on 100,000 numbers, a loop per query is 10¹⁰ steps. Prefix sums make it 200,000.

v
03
11
24
31
45
59
pre
0
1
2
3
4
5
// click an operation above to run it
C++ · prefix.cpp
void prefixSums() {
    vector<int> v = {3, 1, 4, 1, 5, 9};
    vector<int> pre(v.size());
    partial_sum(v.begin(), v.end(), pre.begin());   // running totals
    for (int x : pre) cout << x << " ";
    cout << endl;

    // Sum of v[l..r] in O(1): pre[r] - pre[l - 1]
    int l = 2, r = 4;
    cout << pre[r] - (l ? pre[l - 1] : 0) << endl;  // 4 + 1 + 5 = 10

    vector<int> diff(v.size());
    adjacent_difference(v.begin(), v.end(), diff.begin());
    for (int x : diff) cout << x << " ";
    cout << endl;
}
Output · g++ 13.3 -std=c++17
3 4 8 9 14 23 
10
3 -2 3 -3 4 4
  • adjacent_difference is the reverse: it recovers v from its running totals, and it is the basis of difference arrays for range updates.
Numeric · <numeric>

std::gcd & lcm

#include <numeric>O(log min(a,b))C++17

gcd uses Euclid's rule: gcd(a, b) = gcd(b, a % b), stopping when b is 0. 48 and 18 take three steps: 48 % 18 = 12, 18 % 12 = 6, 12 % 6 = 0.

lcm(a, b) equals a / gcd(a, b) × b. Dividing first keeps the intermediate number small.

// click an operation above to run it
C++ · gcd.cpp
void gcdLcm() {
    cout << gcd(48, 18) << endl;       // 6   (C++17, <numeric>)
    cout << lcm(4, 6) << endl;         // 12
    cout << __gcd(48, 18) << endl;     // older GCC-only name

    int g = gcd(42, 56);               // reduce the fraction 42/56
    cout << 42 / g << "/" << 56 / g << endl;
}
Output · g++ 13.3 -std=c++17
6
12
6
3/4
  • __gcd is a GCC extension from before C++17. It won't compile on MSVC. Prefer std::gcd.
Set algorithms · two sorted ranges

set_union, set_intersection, set_difference

#include <algorithm>O(n + m)inputs must be sorted

These walk two sorted ranges with one pointer each. At every step they compare the two current values, emit something, and advance the smaller side. No hashing, no nested loops.

The output goes through an iterator. back_inserter(u) calls u.push_back for each result, so you don't need to size u in advance.

a
1
3
5
7
b
3
4
5
6
result
empty
// click an operation above to run it
C++ · setops.cpp
void setOperations() {
    vector<int> a = {1, 3, 5, 7}, b = {3, 4, 5, 6};   // both sorted
    vector<int> u, in, d;
    set_union(a.begin(), a.end(), b.begin(), b.end(), back_inserter(u));
    set_intersection(a.begin(), a.end(), b.begin(), b.end(), back_inserter(in));
    set_difference(a.begin(), a.end(), b.begin(), b.end(), back_inserter(d));

    for (int x : u) cout << x << " ";
    cout << endl;
    for (int x : in) cout << x << " ";
    cout << endl;
    for (int x : d) cout << x << " ";
    cout << endl;

    // is every element of `in` also in `a`?
    cout << includes(a.begin(), a.end(), in.begin(), in.end()) << endl;
}
Output · g++ 13.3 -std=c++17
1 3 4 5 6 7 
3 5 
1 7 
1
  • They work on vectors and on sets. They do not work on unordered containers, because those are not sorted.
Reference

complexity cheat sheet

n is the number of elements. "amortized" means fast on average, with an occasional slow step (a vector reallocating). "avg" means average case for hash tables.

ContainerAccess i-thSearchInsertEraseOrdered?Duplicates?
vectorO(1)O(n)back O(1)* · middle O(n)back O(1) · middle O(n)insertion orderyes
arrayO(1)O(n)fixed sizefixed sizeindex orderyes
dequeO(1)O(n)ends O(1) · middle O(n)ends O(1) · middle O(n)insertion orderyes
listO(n)O(n)O(1) at iteratorO(1) at iteratorinsertion orderyes
forward_listO(n)O(n)O(1) after iteratorO(1) after iteratorinsertion orderyes
stringO(1)find O(n·m)back O(1)* · middle O(n)back O(1) · middle O(n)text orderyes
bitset<N>O(1)count O(N/64)fixed N bitsfixed N bitsbit indexon/off
stack / queuetop/front onlynoO(1)O(1)LIFO / FIFOyes
priority_queuetop only O(1)noO(log n)O(log n)max (or min) on topyes
set / mapO(n)O(log n)O(log n)O(log n)sortedno
multiset / multimapO(n)O(log n)O(log n)O(log n + k)sortedyes
unordered_set / mapnoO(1) avgO(1) avgO(1) avgno orderno

Which container should you pick?

You needUseExample
a size that never changesarraydays in each of 12 months
a growing list, index accessvectormarks of 60 students, read marks[i]
add/remove at both endsdequesliding window maximum
undo, bracket matchingstackis "{[()]}" balanced?
process in arrival orderqueueBFS on a grid, print jobs
always grab the largest/smallestpriority_queueDijkstra, top-k scores
unique values, sorted, range queriesset"smallest value ≥ 50" with lower_bound
fast "have I seen this?"unordered_setduplicate detection in 10⁶ numbers
key → value, sorted keysmaproll number → name, printed in order
key → value, just lookupsunordered_mapword frequency count
many on/off flagsbitsetsieve of primes up to 10⁶
range sums, many queriespartial_sumsales between day l and day r
k-th smallest or mediannth_elementmedian of 10⁶ salaries
Reference

common mistakes

Each of these compiles. Most still print something. That is what makes them dangerous.

top() or pop() on an empty stack

It is undefined behavior, not a guaranteed runtime error. The program may keep running with a garbage value.
✕ wrong
st.pop(); st.pop();
st.top();   // stack is empty
✓ right
if (!st.empty()) cout << st.top();

Dereferencing end()

lower_bound, upper_bound and find return end() when nothing matches. Reading *end() is undefined behavior.
✕ wrong
auto ub = st4.upper_bound(214);
cout << *ub;          // ub == end()
if (ub == st4.end()) ...
✓ right
auto ub = st4.upper_bound(214);
if (ub == st4.end()) cout << "Pointing to end";
else cout << *ub;

A comparator that returns true for equal elements

sort requires comp(a, a) == false. Returning true can make std::sort read past the array and crash on inputs with duplicates.
✕ wrong
bool comp(int a, int b) {
    if (a < b) return false;
    else return true;   // true when a == b
}
✓ right
bool comp(int a, int b) {
    return a > b;
}

Using < to compare iterators

Works on vector and deque only. list, set and map iterators have no < and the loop will not compile.
✕ wrong
for (auto i = ls.begin(); i < ls.end(); i++)
✓ right
for (auto i = ls.begin(); i != ls.end(); i++)

Reading map[key] to check if a key exists

operator[] inserts the key with a default value when it is missing. Your map grows silently.
✕ wrong
if (mpp[5] == "") ...   // inserts key 5
✓ right
if (mpp.count(5)) ...
if (mpp.find(5) != mpp.end()) ...

multiset::erase(value) when you meant one copy

erase(value) removes every copy. Pass an iterator to remove one.
✕ wrong
ms.erase(2);   // removes all 2s
✓ right
auto it = ms.find(2);
if (it != ms.end()) ms.erase(it);

Getting the sort range wrong

The last pointer is excluded. sort(nums + 1, nums + 4) sorts indices 1, 2, 3, not 0, 1, 2.
✕ wrong
sort(nums + 1, nums + 4); // "sorts 0 1 2"?
✓ right
sort(nums, nums + 3);     // indices 0, 1, 2

accumulate with an int initial value on big numbers

The init type is the accumulator type. An int init overflows on long long data.
✕ wrong
accumulate(v.begin(), v.end(), 0);
✓ right
accumulate(v.begin(), v.end(), 0LL);

Keeping an iterator across push_back

When a vector reallocates, all old iterators and pointers point at freed memory.
✕ wrong
auto it = vec.begin();
vec.push_back(9);   // may reallocate
cout << *it;        // dangling
✓ right
vec.push_back(9);
auto it = vec.begin();   // take it after

Calling unique and forgetting erase

unique does not change the size. The duplicates are gone from the front, but the tail is still inside the vector.
✕ wrong
sort(v.begin(), v.end());
unique(v.begin(), v.end());
cout << v.size();   // unchanged
✓ right
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());

binary_search on unsorted data

It returns an answer either way. On unsorted input the answer is unreliable.
✕ wrong
vector<int> v = {7, 1, 9, 3};
binary_search(v.begin(), v.end(), 1);  // may say 0
✓ right
sort(v.begin(), v.end());
binary_search(v.begin(), v.end(), 1);  // 1

Treating substr's second argument as an end index

substr(start, length). The second number is how many characters, not where to stop.
✕ wrong
string s = "abcdefg";
s.substr(2, 5);   // "cdefg", not "cde"
✓ right
s.substr(2, 5 - 2);   // "cde": length = end - start

A for_each lambda without &

Taking the element by value changes a copy. The container stays the same.
✕ wrong
for_each(v.begin(), v.end(), [](int x) { x *= 2; });
✓ right
for_each(v.begin(), v.end(), [](int &x) { x *= 2; });
Reference

check yourself

Eleven quick questions. Each answer explains itself when you click.

1. set<int> s = {5, 1, 5, 3}; for (int x : s) cout << x; prints?

2. Which container gives both O(1) push_front and O(1) access by index?

3. map<string,int> m; cout << m["x"] << m.size(); prints?

4. priority_queue<int> pq; push 3, 9, 4. What is pq.top()?

5. multiset<int> ms = {2, 2, 2}; ms.erase(2); ms.size() is?

6. int a[5] = {5, 4, 3, 2, 1}; sort(a, a + 3); a is now?

7. string s = "abcdefg"; cout << s.substr(2, 3); prints?

8. bitset<4> b(5); cout << b; prints?

9. v = {3, 1, 3}; v.erase(unique(v.begin(), v.end()), v.end()); v is?

10. Fastest way to find the median of 1,000,000 numbers?