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

C/C++ 進階實戰:Lambda 表達式、STL 算法與容器深度解析

     編輯:關於C++

Lambda 表達式:現代 C++ 的函數式利器

Lambda 表達式(C++11 引入)允許就地定義匿名函數對象,語法:

[捕獲列表](參數列表) -> 返回類型 { 函數體 }

核心示例

// 1. 基礎用法:for_each + Lambda 累加
vector v = {11, 22, 33, 3, 4, 5};
int sum = 0;
for_each(v.begin(), v.end(), [&sum](int x) { sum += x; });
// sum = 78

// 2. 捕獲模式:[=] 值捕獲,[&] 引用捕獲,[x, &y] 混合
int factor = 10;
auto multiply = [factor](int x) { return x * factor; }; // 值捕獲 factor
auto add_ref = [&sum](int x) { sum += x; };             // 引用捕獲 sum

// 3. 可變 Lambda:mutable 允許修改值捕獲的變量
auto counter = [count = 0]() mutable { return ++count; };
cout << counter() << counter() << counter(); // 1 2 3

STL 算法精選:數據操作的瑞士軍刀

查找類

vector v = {1, 2, 3, 11, 22, 33};

// find: 精確查找
auto it = find(v.begin(), v.end(), 23);
if (it == v.end()) cout << "23玩失蹤";

// find_if: 條件查找(第一個滿足條件的)
auto it2 = find_if(v.begin(), v.end(), [](int x){ return x > 4; });
// 指向 11

// find_if_not: 條件查找(第一個不滿足條件的)
auto it3 = find_if_not(v.begin(), v.end(), [](int x){ return x > 4; });
// 指向 1

修改類

vector v = {1, 2, 3, 11, 22, 33};

// fill: 區間填充
fill(v.begin() + 3, v.end(), 3); // v 變為 {1, 2, 3, 3, 3, 3}

// rotate: 區間旋轉(將 [first, middle) 移到 [middle, last) 之後)
// 相當於左旋 middle-first 位
rotate(v.begin(), v.begin() + 2, v.end()); 
// {1,2,3,3,3,3} → {3,3,3,3,1,2}

// random_shuffle: 隨機打亂(C++14 棄用,改用 shuffle + 隨機引擎)
random_shuffle(v.begin(), v.end());

分區與排序

vector v = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};

// partition: 根據條件分區,滿足條件的在前
// 服務於 quicksort 的 partition 步驟
partition(v.begin(), v.end(), [](int x){ return x == 8; });
// 8 會被移到前面

// partial_sort: 部分排序(取前 k 小)
vector students = {{"A",106}, {"B",101}, {"C",103}, {"D",105}};
partial_sort(students.begin(), students.begin()+2, students.end(),
             [](const Student& a, const Student& b){ return a.score < b.score; });
// 前兩名為分數最低的 B(101) 和 C(103)

// next_permutation: 字典序下一排列(可用於全排列枚舉)
int a[] = {2, 1, 3, 10};
do { print(a); } while (next_permutation(a, a+4));

容器深度剖析

vector:動態陣列,隨機訪問 O(1)

vector v(5);      // 5 個 0
v.push_back(1);        // 尾插
v.insert(v.begin()+1, 999); // 中間插入 O(n)
v.erase(v.begin()+5);  // 中間刪除 O(n)
v.pop_back();          // 尾刪 O(1)
// 迭代器失效規則:插入/刪除/擴容可能導致所有迭代器失效

list:雙向鏈表,插刪 O(1),不支援隨機訪問

list lst = {121, 12, 122, 23};
// lst.sort(); // list 專屬 sort,因為無隨機訪問不能用 std::sort
// fill 需隨機訪問迭代器,list 不支援

multiset:有序多重集,紅黑樹實現,自動排序、允許重複

multiset ms = {3,1,2,1,2,1,2,1};
cout << ms.count(1); // 4 次
auto it = adjacent_find(ms.begin(), ms.end()); // 找相鄰相等元素
// 指向第一對相鄰的 1

實戰技巧總結

需求推薦算法/容器關鍵點
就地修改、累加for_each + [&]Lambda引用捕獲外部變量
條件查找第一個find_if / find_if_not配合 Lambda 表達條件
區間填充/旋轉/打亂fill / rotate / shufflerotate 理解「三段式」參數
取前 k 小/大partial_sort / nth_elementnth_element 平均 O(n) 更快
頻繁中間插刪list / forward_list犧牲隨機訪問換 O(1) 插刪
自動去重+排序set / multiset紅黑樹,查找/插入 O(log n)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved