STL Containers
Quick Notes
Section titled “Quick Notes”STL container quản lý collection theo cấu trúc dữ liệu khác nhau.
Chọn container theo thao tác chính: truy cập ngẫu nhiên, thêm/xóa, tìm kiếm, thứ tự.
std::vector là lựa chọn mặc định tốt khi chưa có nhu cầu đặc biệt.
Syntax
Section titled “Syntax”std::vector<int> nums = {1, 2, 3};std::map<std::string, int> freq;std::priority_queue<int> pq;Container Table
Section titled “Container Table”| Container | Ordered | Duplicate | Typical Complexity |
|---|---|---|---|
vector | index order | yes | access O(1), push back amortized O(1) |
deque | index order | yes | front/back O(1) |
list | insertion order | yes | insert/erase with iterator O(1) |
stack | LIFO | yes | push/pop/top O(1) |
queue | FIFO | yes | push/pop/front O(1) |
priority_queue | heap order | yes | push/pop O(log n), top O(1) |
set | sorted | no | find/insert/erase O(log n) |
multiset | sorted | yes | find/insert/erase O(log n) |
unordered_set | no | no | average O(1), worst O(n) |
map | sorted by key | key no | find/insert/erase O(log n) |
multimap | sorted by key | key yes | find/insert/erase O(log n) |
unordered_map | no | key no | average O(1), worst O(n) |
Example
Section titled “Example”std::vector<int> v;v.push_back(10);v.push_back(20);
std::unordered_map<std::string, int> count;count["cpp"]++;
std::set<int> s = {3, 1, 2};if (s.contains(2)) { std::cout << "found\n";}Common Methods
Section titled “Common Methods”| Container | Common Methods |
|---|---|
| Sequence | push_back, pop_back, front, back, size, empty |
| Set | insert, erase, find, contains, lower_bound |
| Map | operator[], at, insert, erase, find, contains |
| Adapter | push, pop, top/front, empty, size |
Common Mistakes
Section titled “Common Mistakes”- Dùng
map[key]chỉ để kiểm tra tồn tại, vô tình chèn key mới. - Giữ iterator sau khi container bị thay đổi làm iterator invalid.
- Dùng
unordered_mapvới custom key mà chưa định nghĩa hash.
Search Keywords
Section titled “Search Keywords”stl containers container c++ vector deque list stack queue priority_queue set multiset unordered_set map multimap unordered_map độ phức tạp complexity