← Danh sách bài học
⚙️

STL

STL (Standard Template Library) cung cấp container (vector, map, set…), iterator, algorithm (sort, find…) đã tối ưu sẵn. Nắm STL = viết code C++ nhanh và ngắn.

1. vector<T>

Mảng động. push_back, pop_back, size, begin/end, resize, clear. Truy cập v[i] O(1).

2. map<K,V> / unordered_map<K,V>

map: cây đỏ-đen, khoá sắp xếp, O(log n). unordered_map: hash, O(1) trung bình. Dùng cho tra cứu theo khoá.

map<string, int> diem;
diem["An"] = 9;
diem["Binh"] = 7;
for (auto& [ten, d] : diem) cout << ten << ": " << d << endl;

3. set / unordered_set

Tập hợp không trùng lặp. count() để kiểm tra tồn tại, insert() để thêm.

4. queue, stack, priority_queue

queue FIFO, stack LIFO, priority_queue = heap (mặc định max-heap).

5. Algorithm

sort(v.begin(), v.end()), reverse, min_element, max_element, count, find, accumulate (numeric), unique, lower_bound (binary search).

💻 Code mẫu thực chiến

Đếm tần suất từ

Đọc nhiều từ, in mỗi từ + số lần xuất hiện.

#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
    map<string, int> f;
    string w;
    while (cin >> w) f[w]++;
    for (auto& [k, v] : f) cout << k << ": " << v << endl;
}

Top 3 điểm cao

Dùng priority_queue.

#include <queue>
priority_queue<int> pq;
vector<int> diem = {5, 9, 7, 10, 3, 8};
for (int d : diem) pq.push(d);
for (int i = 0; i < 3; i++) { cout << pq.top() << " "; pq.pop(); }
// 10 9 8

Danh bạ nhanh

unordered_map<string, string> tra SĐT theo tên.

unordered_map<string, string> db;
db["Minh"] = "0912345678";
if (db.count("Minh")) cout << db["Minh"];

💡 Mẹo & lưu ý

  • auto& trong range-for để tránh copy.
  • map iterate theo thứ tự khoá; unordered_map không thứ tự.
  • Reserve dung lượng vector khi biết trước để tránh realloc: v.reserve(n).