Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Lambda Function ใน C/C++: ความสำคัญและการใช้งาน


Lambda Function คืออะไร?

Lambda Function** (หรือ Lambda Expression) คือ **Anonymous Function** ที่เขียนแบบ Inline ไม่ต้องประกาศแยก นำเสนอใน **C++11** (C ไม่มี Lambda มาตรฐาน)

Syntax (C++11)


[capture](parameters) -> return_type { body }
  • [capture] - Capture Clause (จับตัวแปรจาก Scope นอก)
  • (parameters) - Parameters (Optional)
  • -> return_type - Return Type (Optional, Deduce ได้)
  • { body } - Function Body

Capture Modes

ตัวอย่างพื้นฐาน


#include 
#include 
#include 

int main() {
    std::vector v = {1, 2, 3, 4, 5};
    
    // Lambda แบบง่าย
    auto print = [](int x) { std::cout << x << ' '; };
    std::for_each(v.begin(), v.end(), print); // 1 2 3 4 5
    
    // Lambda กับ Capture
    int multiplier = 3;
    auto multiply = [multiplier](int x) { return x * multiplier; };
    std::cout << multiply(5); // 15
    
    return 0;
}

Capture by Value vs Reference


int x = 10;

// By Value (Copy)
auto byValue = [x]() { 
    // x ในนี้เป็น Copy ค่า 10
    // ไม่สามารถแก้ x ได้ (ถ้าไม่ใส่ mutable)
};

// By Reference
auto byRef = [&x]() { 
    // x ในนี้คือตัวจริง
    x = 20; // แก้ค่าตัวจริงได้
};

Mutable Lambda


int x = 10;
auto lambda = [x]() mutable { // mutable = เปลี่ยนค่า Capture by Value ได้
    x = 20; // OK แก้ Copy ได้
    std::cout << x; // 20
};
lambda();
std::cout << x; // 10 (ต้นทางไม่เปลี่ยน)

Generic Lambda (C++14)


auto add = [](auto a, auto b) { return a + b; };
std::cout << add(1, 2);       // 3 (int)
std::cout << add(1.5, 2.5);   // 4.0 (double)
std::cout << add("Hello", "World"); // "HelloWorld" (string)

Lambda เป็น Functor (Function Object)

  • Compiler สร้าง **Unique Class** (Closure Type) สำหรับแต่ละ Lambda
  • มี operator() Overload
  • Capture Variables = Member Variables ของ Class นั้น
  • สามารถเก็บใน std::function หรือส่งเป็น Template Parameter ได้

ตัวอย่าง: ใช้กับ STL Algorithms


std::vector v = {5, 2, 8, 1, 9};

// Sort Descending
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });

// Find First Even
auto it = std::find_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; });

// Transform
std::vector squares;
std::transform(v.begin(), v.end(), std::back_inserter(squares),
               [](int x) { return x * x; });

⚠️ C ไม่มี Lambda (Standard C)

  • C ใช้ **Function Pointers** แทน
  • GCC/Clang มี Extension: __attribute__((blocks)) (Apple Blocks)
  • แต่ไม่ใช่ Standard Portable

C Alternative: Function Pointer


#include 
#include 

int compare_int(const void *a, const void *b) {
    return (*(int*)a - *(int*)b);
}

int main() {
    int arr[] = {5, 2, 8, 1, 9};
    qsort(arr, 5, sizeof(int), compare_int); // Function Pointer
    return 0;
}
Captureความหมาย
[=]Capture All by Value (Copy)
[&]Capture All by Reference
[x]Capture x by Value
[&x]Capture x by Reference
[=, &x]All by Value, แต่ x by Reference
[&, x]All by Reference, แต่ x by Value