STL (Standard Template Library) 算法是一組操作容器的通用函數模板,封裝了搜尋、排序、修改、複製等常見操作。掌握它們能讓你用幾行代碼替換幾十行手寫迴圈,代碼更健壯、可讀性更高。
count, count_iffind, find_if, find_end, find_first_of, adjacent_find, search, search_nequal, mismatch, lexicographical_comparefill, fill_n, generate, generate_nfor_each, transformcopy, copy_backwardremove, remove_if, remove_copy, remove_copy_if, unique, unique_copyreplace, replace_ifsort, stable_sort, partial_sortpartition, stable_partitionbinary_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; }
[first, last) 操作,與容器類型解耦。unique 僅移除相鄰重複元素,故必須先 sort。remove 只是覆蓋,真正釋放空間需呼叫容器的 erase。_if 後綴算法(如 remove_if、count_if)。STL 算法是 C++ 開發者的利器。建議先熟練 sort, find, copy, transform, remove/erase 等高頻組合,再按需學習其餘算法。實戰中多查閱 <algorithm> 文檔,將複雜邏輯轉化為聲明式代碼,事半功倍。