Skip to content

🔧 STL Algorithms — Tổng quan

C++ STL cung cấp hơn 100 algorithms sẵn có. Thay vì viết loops thủ công, bạn dùng các hàm đã được tối ưu và test kỹ.

Philosophy: Algorithms + Iterators + Containers

┌─────────────────────────────────────────────────────────────────┐
│                    STL ARCHITECTURE                             │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│   CONTAINERS                ITERATORS              ALGORITHMS  │
│   ──────────               ──────────             ───────────  │
│   vector                      ↓                    sort        │
│   list          ────►    begin/end    ────►        find        │
│   map                         ↓                    transform   │
│   set                  (abstraction)               accumulate  │
│                                                    copy        │
│                                                    ...         │
│                                                                 │
│  Algorithms KHÔNG biết container cụ thể!                       │
│  Chúng chỉ làm việc với iterators.                             │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Headers

cpp
#include <algorithm>  // sort, find, transform, copy, ...
#include <numeric>    // accumulate, iota, partial_sum, ...
#include <functional> // std::greater, std::less, std::function

Algorithm Categories

1. Non-Modifying Sequence Operations

AlgorithmDescription
std::findTìm phần tử đầu tiên khớp
std::find_ifTìm phần tử thỏa điều kiện
std::countĐếm occurrences
std::count_ifĐếm theo điều kiện
std::all_ofKiểm tra tất cả thỏa predicate
std::any_ofKiểm tra có ít nhất 1 thỏa
std::none_ofKiểm tra không có ai thỏa
std::for_eachThực thi function cho mỗi element

2. Modifying Sequence Operations

AlgorithmDescription
std::copyCopy elements
std::transformTransform và output
std::fillFill với 1 giá trị
std::generateGenerate với function
std::replaceReplace giá trị
std::removeRemove (cần erase sau)
std::uniqueRemove consecutive duplicates
std::reverseĐảo ngược
std::rotateXoay elements

3. Sorting Operations

AlgorithmDescription
std::sortSort range
std::stable_sortSort giữ relative order
std::partial_sortSort first N
std::nth_elementPartition at nth
std::is_sortedCheck if sorted

4. Binary Search (on sorted ranges)

AlgorithmDescription
std::binary_searchCheck if exists
std::lower_boundFirst not less than
std::upper_boundFirst greater than
std::equal_rangeBoth bounds

5. Numeric Operations (<numeric>)

AlgorithmDescription
std::accumulateSum/reduce
std::inner_productDot product
std::partial_sumPrefix sums
std::adjacent_differenceDifferences
std::iotaFill with incrementing values

Quick Examples

cpp
#include <algorithm>
#include <numeric>
#include <vector>
#include <iostream>

int main() {
    std::vector<int> v = {5, 2, 8, 1, 9, 3, 7, 4, 6};
    
    // Sort
    std::sort(v.begin(), v.end());
    // [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    // Find
    auto it = std::find(v.begin(), v.end(), 5);
    if (it != v.end()) {
        std::cout << "Found at index: " << (it - v.begin()) << std::endl;
    }
    
    // Sum
    int sum = std::accumulate(v.begin(), v.end(), 0);
    std::cout << "Sum: " << sum << std::endl;  // 45
    
    // Count
    int count = std::count_if(v.begin(), v.end(), 
                              [](int x) { return x > 5; });
    std::cout << "Count > 5: " << count << std::endl;  // 4
    
    // Transform (double each)
    std::transform(v.begin(), v.end(), v.begin(),
                   [](int x) { return x * 2; });
    
    return 0;
}

Part 2 Structure

TopicDescription
Lambda ExpressionsExtensive lambda tutorial
Sorting & ComparatorsCustom sort rules
Searchingfind, binary_search
Transform & ReduceFunctional operations
Code GolfSTL power demonstrations

➡️ Tiếp theo

Tiếp theo: Lambda Expressions — Học cách viết inline functions.