Skip to content
Laviyx Learn

Try

C++ STL Cheat Sheet

vector, string, map, set, unordered_map, stack, queue, and the most useful algorithms.

Updated

Choosing a container#

NeedContainerHeader
A list you loop over (default choice)std::vector<T><vector>
Fixed size known at compile timestd::array<T, N><array>
Fast lookup by key, sorted keysstd::map<K, V><map>
Fast lookup by key, any orderstd::unordered_map<K, V><unordered_map>
Unique values, sortedstd::set<T><set>
Unique values, any orderstd::unordered_set<T><unordered_set>
Last in, first outstd::stack<T><stack>
First in, first outstd::queue<T><queue>
Largest (or smallest) firststd::priority_queue<T><queue>
Add/remove at both endsstd::deque<T><deque>

vector#

C++
std::vector<int> v = {3, 1, 2};
std::vector<int> zeros(5);         // 0 0 0 0 0
std::vector<int> one{5};           // a single element: 5

v.push_back(4);                    // add at the end
v.pop_back();                      // remove the last
v.size();  v.empty();              // 3, false
v[0];  v.at(0);                    // at() checks bounds
v.front();  v.back();
v.insert(v.begin() + 1, 9);        // insert at index 1
v.erase(v.begin());                // remove index 0
v.reserve(1000);                   // pre-allocate
v.clear();
std::erase_if(v, [](int x) { return x < 0; });   // C++20

map and unordered_map#

C++
std::map<std::string, int> ages = {{"Asha", 21}};

ages["Ravi"] = 25;                 // insert or update ([] inserts if missing!)
ages.at("Asha");                   // 21, throws if missing
ages.contains("John");             // false (C++20)
ages.count("Asha");                // 1

if (auto it = ages.find("Ravi"); it != ages.end()) {
    std::cout << it->first << ' ' << it->second;
}

ages.insert({"Meera", 23});        // does not overwrite
ages.insert_or_assign("Meera", 24);
ages.erase("Ravi");

for (const auto& [name, age] : ages) { }   // sorted by key (map only)

std::unordered_map has the same interface, O(1) average lookup, and no order.

set and unordered_set#

C++
std::set<int> s = {5, 1, 4, 1};    // {1, 4, 5}
s.insert(3);
s.erase(4);
s.contains(3);                     // true (C++20)
auto [it, added] = s.insert(3);    // added == false: already present
*s.begin();  *s.rbegin();          // smallest, largest
s.lower_bound(2);                  // first element >= 2

stack, queue, priority_queue#

C++
std::stack<int> st;   st.push(1);  st.top();   st.pop();
std::queue<int> q;    q.push(1);   q.front();  q.pop();

std::priority_queue<int> max_heap;                                     // largest on top
std::priority_queue<int, std::vector<int>, std::greater<int>> min_heap;   // smallest on top
max_heap.push(5);  max_heap.top();  max_heap.pop();
// pop() returns nothing: read top()/front() first, and check empty()

Iterators#

C++
v.begin();  v.end();                // [first, one-past-last)
v.rbegin(); v.rend();               // reverse
auto it = std::find(v.begin(), v.end(), 7);
if (it != v.end()) { }              // always compare with end()
std::distance(v.begin(), it);       // index
it = v.erase(it);                   // erase returns the next valid iterator

Algorithms (<algorithm>, <numeric>)#

C++
std::sort(v.begin(), v.end());                        // ascending
std::sort(v.begin(), v.end(), std::greater<int>());   // descending
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
std::stable_sort(v.begin(), v.end());                 // keeps equal elements in order

std::find(v.begin(), v.end(), x);
std::find_if(v.begin(), v.end(), [](int n) { return n < 0; });
std::count(v.begin(), v.end(), x);
std::count_if(v.begin(), v.end(), [](int n) { return n % 2 == 0; });
std::any_of(v.begin(), v.end(), [](int n) { return n > 100; });

std::min_element(v.begin(), v.end());                 // iterator
std::max(a, b);  std::min({a, b, c});
std::accumulate(v.begin(), v.end(), 0);               // sum (start value sets the type)
std::iota(v.begin(), v.end(), 1);                     // 1, 2, 3, ...

std::reverse(v.begin(), v.end());
std::binary_search(v.begin(), v.end(), x);            // sorted input only
std::lower_bound(v.begin(), v.end(), x);              // first >= x (sorted)
v.erase(std::unique(v.begin(), v.end()), v.end());    // remove adjacent duplicates
std::transform(v.begin(), v.end(), v.begin(), [](int n) { return n * 2; });

C++20 ranges#

C++
std::ranges::sort(v);
std::ranges::find(v, 7);
for (int x : v | std::views::filter([](int n) { return n % 2 == 0; })
               | std::views::transform([](int n) { return n * n; })) { }
for (int i : std::views::iota(1, 6)) { }        // 1..5

Complexity at a glance#

Operationvectormap / setunordered_map / set
Index accessO(1)––
FindO(n)O(log n)O(1) average
Insert / erase at endO(1)*––
Insert / erase by key–O(log n)O(1) average
SortO(n log n)always sortednot ordered

* amortized

Want the full explanations? Go to the Learn C++ course →