STL Algorithms
Quick Notes
Section titled “Quick Notes”STL algorithms làm việc qua iterator, nên dùng được với nhiều container.
Hầu hết nằm trong <algorithm>, riêng std::accumulate nằm trong <numeric>.
Với binary search, range phải được sort trước.
Syntax
Section titled “Syntax”std::sort(v.begin(), v.end());auto it = std::find(v.begin(), v.end(), 7);Quick Examples
Section titled “Quick Examples”std::sort(v.begin(), v.end());std::stable_sort(v.begin(), v.end(), cmp);std::reverse(v.begin(), v.end());
auto it = std::find(v.begin(), v.end(), 5);int c = std::count(v.begin(), v.end(), 5);
auto lo = std::lower_bound(v.begin(), v.end(), 10);auto hi = std::upper_bound(v.begin(), v.end(), 10);bool ok = std::binary_search(v.begin(), v.end(), 10);
auto mn = std::min_element(v.begin(), v.end());auto mx = std::max_element(v.begin(), v.end());int sum = std::accumulate(v.begin(), v.end(), 0);Complexity
Section titled “Complexity”| Algorithm | Complexity |
|---|---|
sort | O(n log n) |
stable_sort | O(n log n) |
reverse | O(n) |
find, count | O(n) |
lower_bound, upper_bound, binary_search | O(log n) on random access sorted range |
min_element, max_element | O(n) |
accumulate | O(n) |
Common Mistakes
Section titled “Common Mistakes”- Gọi
lower_boundtrên vector chưa sort. - Quên kiểm tra iterator khác
.end()trước khi dereference. - Dùng initial value
0trongaccumulatelàm overflow khi cầnlong long.
Search Keywords
Section titled “Search Keywords”stl algorithms thuật toán stl sort stable_sort reverse find count lower_bound upper_bound binary_search min_element max_element accumulate