iT邦幫忙

2025 iThome 鐵人賽

DAY 27
0
自我挑戰組

C++入門即放棄系列 第 27

[DAY27]不一樣的表達!

  • 分享至 

  • xImage
  •  

Lambda是甚麼?

📌 不用取名字的函式,適合寫小段邏輯

[capture](參數) -> 回傳型別 
{
    函式內容
};
#include <iostream>
using namespace std;
int main() 
{
    auto add = [](int a, int b) { return a + b; };
    cout << add(3, 4) << endl; 
}

搭配 STL

#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 會讓編譯器自動判斷變數型別

好處是 程式碼簡短,而且遇到長型別(例如迭代器)時很方便

auto x = 10;    
auto y = 3.14;   
auto s = "Hello"; 

搭配STL

#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 則讓程式碼更簡潔

尤其在處理複雜型別時非常方便


上一篇
[DAY26]預料中的例外?
下一篇
[DAY28]同時做好多事情!
系列文
C++入門即放棄28
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言