Skip to content

STL Algorithms

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.

std::sort(v.begin(), v.end());
auto it = std::find(v.begin(), v.end(), 7);
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);
AlgorithmComplexity
sortO(n log n)
stable_sortO(n log n)
reverseO(n)
find, countO(n)
lower_bound, upper_bound, binary_searchO(log n) on random access sorted range
min_element, max_elementO(n)
accumulateO(n)
  • Gọi lower_bound trên vector chưa sort.
  • Quên kiểm tra iterator khác .end() trước khi dereference.
  • Dùng initial value 0 trong accumulate làm overflow khi cần long long.

stl algorithms thuật toán stl sort stable_sort reverse find count lower_bound upper_bound binary_search min_element max_element accumulate