C++ STL มี generic algorithms อย่าง std::for_each แต่การสร้าง functor แบบเดิม煩瑣 (verbose) C++11 เพิ่ม lambda expressions (anonymous functions) เพื่อแก้ปัญหานี้
ตัวอย่าง
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> myvector = {1, 2, 3};
for_each(myvector.begin(), myvector.end(), [](int x) {
cout << x * x << endl;
});
}
ผลลัพธ์
1 4 9
Syntax: [capture](parameters) -> return_type { body }
[]- capture clause (ดึงตัวแปรจาก scope นอกเข้ามา)(int x)- parameters-> double- return type (optional ถ้า deducible){ ... }- function body
ตัวอย่างระบุ return type ชัดเจน
[](int x) -> double { return x / 2.0; }
รายละเอียดเพิ่มเติม: StackOverflow: What is a lambda expression in C++11?