Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Thư viện mẫu chuẩn C++ (STL - Standard Template Library)

STL (Standard Template Library)** là thư viện phần mềm cho C++, ảnh hưởng lớn đến C++ Standard Library. Cung cấp 4 thành phần: algorithms, containers, functions, iterators. Lưu ý: thuật ngữ "STL" không xuất hiện trong chuẩn ISO 14882. Gọi C++ Standard Library là STL là sai – STL là subset của Standard Library.

1. Containers (Container)

Đối tượng lưu trữ dữ liệu.

  • Sequence containers: vector, deque, list, array (C++11), forward_list (C++11).
  • Associative containers: set, multiset, map, multimap.
  • Unordered associative (hash): unordered_set, unordered_multiset, unordered_map, unordered_multimap (C++11).
  • Container adaptors: stack, queue, priority_queue (dùng container khác làm backend).

2. Iterators (Iterator)

Đối tượng cho phép duyệt container. 5 loại:

Loại Khả năng
Input Đọc sequence (read-only, single-pass)
Output Ghi sequence (write-only, single-pass)
Forward Đọc/ghi, tiến tới (single-pass)
Bidirectional Forward + lùi lại (list, set, map)
Random Access Nhảy tự do bất kỳ bước (vector, deque, array)

Iterator là chìa khóa cho tính generic của STL – algorithm làm việc trên iterator chứ không phải container cụ thể.

3. Algorithms (Algorithm)

Hàm thiết kế để dùng trên range (phạm vi) phần tử – bất kỳ sequence nào truy cập được qua iterator/con trỏ (array, STL container).

Ví dụ: sort, binary_search, find, min_element, max_element, transform, accumulate, for_each, copy, remove_if...

Tất cả algorithm hoạt động trên bất kỳ kiểu dữ liệu thỏa mãn yêu cầu iterator (template).

4. Functions / Function Objects (Functors)

STL cung cấp function object, predicate, binder, adapter để tùy chỉnh hành vi algorithm.

STL vs C++ Standard Library

STL ⊂ C++ Standard Library. Standard Library còn bao gồm: I/O streams, localization, diagnostics, utilities, numerics, threading, filesystem, regex, atomic, v.v.