> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hnuicpc.tech/llms.txt
> Use this file to discover all available pages before exploring further.

# STLs 2

> Tutorial for Sheet 6 — Advanced STL containers and algorithms: priority queues, deques, and more.

<iframe width="100%" height="400" src="https://www.youtube.com/embed/U7kZB5Xqggc" title="Level 0 Session 6 Recording" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen />

## Priority Queue

A **priority queue** is like a heap. By default, it's a **max-heap** (the largest element is always at the top).

```cpp theme={null}
priority_queue<int> pq; // Max-heap

pq.push(10);
pq.push(30);
pq.push(20);

cout << pq.top(); // 30
pq.pop(); // Remove 30
cout << pq.top(); // 20
```

### Min-Heap

To make it a **min-heap**:

```cpp theme={null}
priority_queue<int, vector<int>, greater<int>> pq; // Min-heap
```

## Deque (Double-Ended Queue)

A **deque** allows insertion and deletion from both ends in $O(1)$.

```cpp theme={null}
deque<int> dq;
dq.push_back(10);
dq.push_front(20);

cout << dq.front(); // 20
cout << dq.back(); // 10

dq.pop_front();
dq.pop_back();
```

## Lower Bound and Upper Bound

Very useful for binary search on sorted containers.

* `lower_bound`: Returns an iterator to the first element $\ge$ value.
* `upper_bound`: Returns an iterator to the first element $>$ value.

```cpp theme={null}
vector<int> v = {1, 3, 3, 5, 7};
auto it1 = lower_bound(v.begin(), v.end(), 3); // points to first 3
auto it2 = upper_bound(v.begin(), v.end(), 3); // points to 5
```

## Custom Sorting with STL

You can use `std::sort` with custom comparators or use `std::greater<T>()`.

```cpp theme={null}
sort(v.begin(), v.end(), greater<int>()); // Sort descending
```

## Practice

<Card title="Sheet 6: STLs 2" icon="list-check" href="/level-0/sheets/sheet-6" horizontal>
  Practice problems for this tutorial.
</Card>
