首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ STL 算法全攻略:分類、應用與實戰代碼

     編輯:關於C++

什麼是 STL 算法?

STL (Standard Template Library) 算法是一組操作容器的通用函數模板,封裝了搜尋、排序、修改、複製等常見操作。掌握它們能讓你用幾行代碼替換幾十行手寫迴圈,代碼更健壯、可讀性更高。

算法分類速查表

非變序算法(不改變元素順序)

  • 計數:count, count_if
  • 搜尋:find, find_if, find_end, find_first_of, adjacent_find, search, search_n
  • 比較:equal, mismatch, lexicographical_compare

變序算法(可能改變元素順序或值)

  • 初始化:fill, fill_n, generate, generate_n
  • 修改:for_each, transform
  • 複製:copy, copy_backward
  • 刪除:remove, remove_if, remove_copy, remove_copy_if, unique, unique_copy
  • 替換:replace, replace_if
  • 排序:sort, stable_sort, partial_sort
  • 分區:partition, stable_partition
  • 有序區間專用:binary_search, lower_bound, upper_bound

實戰範例:常用算法演示

以下完整程式碼展示排序、去重、二分搜尋、有序插入等高頻操作:

#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <string>
using namespace std;

template <typename T>
struct PrintClass {
    void operator()(const T& elem) const { cout << elem << " "; }
};

template <typename T>
bool isEven(const T& number) { return (number % 2) == 0; }

template <typename T>
T addData(const T& v1, const T& v2) { return v1 + v2; }

void tsort() {
    vector<string> vec1 = {"tom", "tim", "tim", "tam", "tam", "kim", "kim"};
    for_each(vec1.begin(), vec1.end(), PrintClass<string>()); cout << endl;

    sort(vec1.begin(), vec1.end());               // 排序
    for_each(vec1.begin(), vec1.end(), PrintClass<string>()); cout << endl;

    bool found = binary_search(vec1.begin(), vec1.end(), "tom"); // 二分搜尋
    if (found) cout << "find ok" << endl;

    auto ite = unique(vec1.begin(), vec1.end());  // 去重(需先排序)
    vec1.erase(ite, vec1.end());
    for_each(vec1.begin(), vec1.end(), PrintClass<string>()); cout << endl;

    // 有序插入:lower_bound/upper_bound 返回插入位置
    string lowerStr = "ad";
    ite = lower_bound(vec1.begin(), vec1.end(), lowerStr);
    vec1.insert(ite, lowerStr);
    for_each(vec1.begin(), vec1.end(), PrintClass<string>()); cout << endl;

    string upperStr = "ss";
    ite = upper_bound(vec1.begin(), vec1.end(), upperStr);
    vec1.insert(ite, upperStr);
    for_each(vec1.begin(), vec1.end(), PrintClass<string>()); cout << endl;
}

int main() { tsort(); return 0; }

關鍵技巧總結

  1. 迭代器為核心:所有算法以迭代器區間 [first, last) 操作,與容器類型解耦。
  2. 去重必先排序:unique 僅移除相鄰重複元素,故必須先 sort。
  3. 刪除 = remove + erase:remove 只是覆蓋,真正釋放空間需呼叫容器的 erase。
  4. 自定義判斷邏輯:善用 Lambda 或函數物件配合 _if 後綴算法(如 remove_if、count_if)。

結語

STL 算法是 C++ 開發者的利器。建議先熟練 sort, find, copy, transform, remove/erase 等高頻組合,再按需學習其餘算法。實戰中多查閱 <algorithm> 文檔,將複雜邏輯轉化為聲明式代碼,事半功倍。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved