📌 不用取名字的函式,適合寫小段邏輯
[capture](參數) -> 回傳型別
{
函式內容
};
#include <iostream>
using namespace std;
int main()
{
auto add = [](int a, int b) { return a + b; };
cout << add(3, 4) << endl;
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> nums = {5, 2, 9, 1};
sort(nums.begin(), nums.end(), [](int a, int b)
{
return a > b;
});
for (int n : nums) cout << n << " ";
}
📌 這樣不用額外寫比較函式
📌 auto
會讓編譯器自動判斷變數型別
好處是 程式碼簡短,而且遇到長型別(例如迭代器)時很方便
auto x = 10;
auto y = 3.14;
auto s = "Hello";
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> score = {{"Alice", 90}, {"Bob", 80}};
for (auto& p : score) {
cout << p.first << " -> " << p.second << endl;
}
}
📌 不用寫 map<string, int>::iterator
,程式更清楚
📌 Lambda 讓我們能快速定義小函式
適合用在 STL 算法中
省去額外寫函式的麻煩
📌 auto 則讓程式碼更簡潔
尤其在處理複雜型別時非常方便