C++ lambda 表示式
lambda 是寫在程式碼中間的匿名函式,比如 [](int a, int b) { return a > b; },常傳給 std::sort 當比較規則;[] 裡寫要捕獲的外部變數。
第 12 課降序排序寫的是 std::greater<int>(),第 14 課按成員排序要在上面另寫一個比較函式。其實可以在呼叫 sort 的地方,就地寫一個小函式,這叫 lambda 表示式:
1#include <algorithm>2#include <iostream>3#include <vector>4 5int main() {6 std::vector<int> scores{72, 95, 88, 60};7 std::sort(scores.begin(), scores.end(), [](int a, int b) { return a > b; });8 for (int s : scores) {9 std::cout << s << " ";10 }11 std::cout << '\n';12 return 0;13}
95 88 72 60
[](int a, int b) { return a > b; } 就是一個沒有名字的函式:兩個引數,a 比 b 大就返回 true,意思是「大的排前面」。sort 每比較兩個元素,就呼叫它一次。
把 [](int a, int b) { return a > b; } 交給 std::sort,排出來是什麼順序?
sort 問 lambda:「a 該排在 b 前面嗎?」a > b 時回答 true,大的就排到前面去了。lambda 的樣子
一個 lambda 有三部分:方括號 [](叫捕獲,「捕獲:用外面的變數」那一關講)、圓括號裡的引數、花括號裡的函式體。返回型別不用寫,編譯器從 return 推出來。
lambda 也可以存進變數,像函式一樣呼叫。它的型別只有編譯器知道,所以用 auto:
auto with_tax① = []②(double price)③ { return price * 1.1; }④;- ①存進變數:型別只有編譯器知道,所以寫 auto
- ②捕獲:這裡什麼也不用
- ③引數,和普通函式一樣
- ④函式體:返回 double,編譯器從 return 推出來
1#include <iostream>2 3int main() {4 auto with_tax = [](double price) { return price * 1.1; };5 auto is_even = [](int n) { return n % 2 == 0; };6 std::cout << with_tax(50) << '\n';7 std::cout << with_tax(200) << '\n';8 std::cout << is_even(7) << '\n';9 return 0;10}
55 220 0
點單步:每次呼叫 with_tax,畫面上和普通函式一樣多出一層,price 是這一次的值。
這段程式顯示什麼?
1#include <iostream>2 3int main() {4 auto twice = [](int n) { return n * 2; };5 std::cout << twice(3) + twice(4) << '\n';6 return 0;7}
twice 是一個把數乘 2 的 lambda。twice(3) 是 6,twice(4) 是 8,加起來 14。給 sort 用
按成員排序,以前要另寫一個函式,現在比較的規矩就寫在 sort 旁邊,讀的人不用往上翻:
1#include <algorithm>2#include <iostream>3#include <string>4#include <vector>5 6struct Student {7 std::string name;8 int score;9};10 11int main() {12 std::vector<Student> list{{"小林", 82}, {"小周", 95}, {"小陳", 76}};13 std::sort(list.begin(), list.end(), [](const Student& a, const Student& b) {14 return a.score > b.score;15 });16 for (const auto& s : list) {17 std::cout << s.name << " " << s.score << '\n';18 }19 return 0;20}
小周 95 小林 82 小陳 76
引數寫 const Student&,不復制、也不改(第 10 課)。lambda 的函式體可以有好幾行,換行寫,和普通函式一樣。
便宜的排前面
✓用 std::sort 和一個 lambda,按價格從低到高排好商品,再按順序顯示名字。程式要顯示三行:雞蛋、牛奶、咖啡豆。
雞蛋 牛奶 咖啡豆
1#include <algorithm>2#include <iostream>3#include <string>4#include <vector>5 6struct Product {7 std::string name;8 double price;9};10 11int main() {12 std::vector<Product> cart{{"咖啡豆", 68}, {"雞蛋", 15.5}, {"牛奶", 22}};13 // 在這裡排序14 for (const auto& p : cart) {15 std::cout << p.name << '\n';16 }17 return 0;18}
count_if 和 find_if
<algorithm> 裡很多函式名字帶 _if,要的都是一個「問一個元素,回答 true 或 false」的函式。std::count_if 數有幾個回答 true;std::find_if 找第一個回答 true 的,返回指著它的迭代器,找不到就是 end():
1#include <algorithm>2#include <iostream>3#include <vector>4 5int main() {6 std::vector<int> scores{72, 58, 91, 45, 66};7 auto failed = std::count_if(scores.begin(), scores.end(), [](int s) { return s < 60; });8 std::cout << "不及格:" << failed << " 人\n";9 auto it = std::find_if(scores.begin(), scores.end(), [](int s) { return s > 90; });10 if (it != scores.end()) {11 std::cout << "第一個超過 90 的:" << *it << '\n';12 }13 return 0;14}
不及格:2 人 第一個超過 90 的:91
和第 12 課的 std::count、std::find 比:那兩個只能數、找「等於某個值」的;帶 _if 的,條件隨你寫。(迭代器第 27 課再細講,現在知道 *it 取值就夠了。)
熱天有幾天
✓用 std::count_if 數一數 temps 裡有幾天高於 hot(捕獲它)。程式要顯示 高溫:3 天。
高溫:3 天
1#include <algorithm>2#include <iostream>3#include <vector>4 5int main() {6 std::vector<int> temps{29, 33, 35, 31, 36, 28};7 int hot = 32;8 // 在這裡數9 return 0;10}
for_each
std::for_each 對每個元素呼叫一次你給的函式。引數寫成引用,就能改元素:
1#include <algorithm>2#include <iostream>3#include <vector>4 5int main() {6 std::vector<double> prices{20, 35, 12.5};7 std::for_each(prices.begin(), prices.end(), [](double& p) { p = p * 0.8; });8 std::for_each(prices.begin(), prices.end(), [](double p) {9 std::cout << p << " 元\n";10 });11 return 0;12}
16 元 28 元 10 元
說實話,這樣的事用範圍 for 一樣清楚。for_each 的好處是:手裡已經有一個存在變數裡的 lambda 時,直接交給它就行。
這段程式顯示什麼?
1#include <algorithm>2#include <iostream>3#include <vector>4 5int main() {6 std::vector<int> v{1, 2, 3};7 std::for_each(v.begin(), v.end(), [](int x) { x = x * 10; });8 std::cout << v[0] + v[1] + v[2] << '\n';9 return 0;10}
int x,不帶 &:每次拿到的是元素的一份複製,改的是複製,v 裡還是 1、2、3,和是 6。要改元素,引數寫成 int& x。捕獲:用外面的變數
lambda 裡想用外面的變數,比如一個及格線,直接寫會編譯錯誤:
1#include <algorithm>2#include <iostream>3#include <vector>4 5int main() {6 std::vector<int> scores{72, 58, 91, 45, 66};7 int pass_line = 70;8 auto passed = std::count_if(scores.begin(), scores.end(), [](int s) { return s >= pass_line; });9 std::cout << passed << '\n';10 return 0;11}
main.cpp: In lambda function:
main.cpp:8:87: error: 'pass_line' is not captured
8 | auto passed = std::count_if(scores.begin(), scores.end(), [](int s) { return s >= pass_line; });
| ^~~~~~~~~'pass_line' is not captured:pass_line 沒有被捕獲。lambda 預設看不到外面的區域性變數,要在方括號裡列出來,叫捕獲。寫成 [pass_line] 就好了,結果是 2。
[pass_line] 是按值捕獲:建 lambda 的那一刻,把 pass_line 的值複製一份帶進去。之後外面再改,lambda 裡的不變:
這段程式顯示什麼?
1#include <iostream>2 3int main() {4 int bonus = 5;5 auto add_bonus = [bonus](int s) { return s + bonus; };6 bonus = 100;7 std::cout << add_bonus(80) << '\n';8 return 0;9}
bonus 是 5,複製了一份進去。第 6 行改的是外面的 bonus,lambda 裡那份還是 5,所以是 85。按引用捕獲
要讓 lambda 改外面的變數,或者看到它最新的值,就按引用捕獲:[&total]。lambda 裡的 total 是外面那個的引用:
1#include <algorithm>2#include <iostream>3#include <vector>4 5int main() {6 std::vector<int> steps{4200, 8100, 6500, 9900};7 int total = 0;8 int good_days = 0;9 int goal = 6000;10 std::for_each(steps.begin(), steps.end(), [&total, &good_days, goal](int s) {11 total += s;12 if (s >= goal) {13 good_days++;14 }15 });16 std::cout << "一共 " << total << " 步," << good_days << " 天達標\n";17 return 0;18}
一共 28700 步,3 天達標
點單步:lambda 每執行一次,main 裡的 total 和 good_days 就變一次。goal 只看不改,按值捕獲就行。
| 寫法 | 意思 |
|---|---|
[] | 什麼也不捕獲 |
[x] | 複製 x |
[&x] | 引用 x |
[=] | 用到的外面變數都複製 |
[&] | 用到的外面變數都引用 |
注意: 按值捕獲的變數在 lambda 裡是隻讀的,[total](int s) { total += s; } 是編譯錯誤。按引用捕獲時要小心:lambda 用的時候,被引用的變數必須還活著。
[bonus](int s) { return s + bonus; }85建的時候複製了一份 5[&bonus](int s) { return s + bonus; }180用的就是外面的 bonus,現在是 100lambda 要給外面的 count 加 1,方括號裡寫什麼?
[&count]。[count] 是一份只讀的複製,count++ 編譯不過;[] 什麼也沒捕獲,根本看不到 count。修好它:改不了的總數
✓這段程式碼想用 for_each 把賬單加起來,卻編譯不過。只加一個字元,讓程式顯示 合計:86。
合計:86
1#include <algorithm>2#include <iostream>3#include <vector>4 5int main() {6 std::vector<int> bills{30, 12, 44};7 int total = 0;8 std::for_each(bills.begin(), bills.end(), [total](int b) { total += b; });9 std::cout << "合計:" << total << '\n';10 return 0;11}
std::function
lambda 的型別寫不出來,存進變數靠 auto。可要是想讓一個變數先存這個 lambda、以後換成那個,或者寫一個「引數是一個函式」的函式,就用 <functional> 裡的 std::function。尖括號裡寫「返回型別(引數型別)」:
1#include <functional>2#include <iostream>3#include <vector>4 5void show_prices(const std::vector<double>& prices, std::function<double(double)> rule) {6 for (double p : prices) {7 std::cout << rule(p) << " ";8 }9 std::cout << '\n';10}11 12int main() {13 std::vector<double> prices{20, 50, 120};14 std::function<double(double)> rule = [](double p) { return p; };15 show_prices(prices, rule);16 rule = [](double p) { return p * 0.9; };17 show_prices(prices, rule);18 double cut = 15;19 show_prices(prices, [cut](double p) { return p >= 100 ? p - cut : p; });20 return 0;21}
20 50 120 18 45 108 20 50 105
std::function<double(double)> 能裝下任何「給一個 double、還一個 double」的東西:不同的 lambda,帶捕獲的也行,普通函式也行。show_prices 不管規矩是什麼,只管呼叫它。(最後一個 lambda 裡的 條件 ? 甲 : 乙:條件成立取甲,不然取乙。)
std::function<bool(int)> check; 能裝下哪一個?
bool(int) 的意思是「給一個 int,還一個 bool」。第二個不要引數,第三個要的是 std::string,都不能拿一個 int 來呼叫。這一課學會了
- lambda 是就地寫的小函式:
[捕獲](引數) { 函式體 },返回型別自己推;存進變數用auto。 - 給
std::sort一個 lambda 定排序規矩,比如[](int a, int b) { return a > b; }。 std::count_if、std::find_if要一個回答true/false的 lambda;std::for_each對每個元素呼叫一次。- lambda 要用外面的區域性變數,得捕獲:
[x]複製一份(建的時候的值,只讀),[&x]是引用(能改,看到最新的值)。 [=]全部複製,[&]全部引用。std::function<返回型別(引數型別)>能裝下各種函式和 lambda,用來存起來、換掉,或者當引數傳。