ฟังก์ชัน std::transform เป็นอัลกอริทึมพื้นฐานใน C++ Standard Template Library (STL) ที่อยู่ใน Header <algorithm> ใช้สำหรับนำฟังก์ชันหรือ Operation ไปประยุกต์กับทุก Element ใน Range (Container/Array) และเก็บผลลัพธ์ไว้ใน Destination Range
สองโหมดการทำงาน
- Unary Operation (ดำเนินการหนึ่งอินพุต): รับ Element เดียว ผ่านฟังก์ชัน Unary แล้วคืนค่าผลลัพธ์
- Binary Operation (ดำเนินการสองอินพุต): รับ Element คู่จากสอง Range มาประมวลผลด้วยฟังก์ชัน Binary
1. Unary Operation Mode
เหมาะสำหรับการแปลงค่าแต่ละตัวอย่าง เช่น ยกกำลังสอง, แปลงตัวพิมพ์เล็กเป็นใหญ่, คำนวณค่าสัมบูรณ์
ตัวอย่าง: ยกกำลังสองของ Array
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int square(int x) {
return x * x;
}
int main() {
vector<int> arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
vector<int> res(arr.size());
// transform(First, Last, Result, UnaryOp)
transform(arr.begin(), arr.end(), res.begin(), square);
for (int val : res)
cout << val << " ";
// Output: 1 4 9 16 25 36 49 64 81 100
return 0;
}
2. Binary Operation Mode
ใช้เมื่อต้องการดำเนินการระหว่าง Element คู่จากสอง Container เช่น บวก, คูณ, เปรียบเทียบ
ตัวอย่าง: คูณ Element-wise ของสอง Array
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int multiply(int x, int y) {
return x * y;
}
int main() {
vector<int> arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
vector<int> arr2 = {54, 21, 32, 65, 58, 74, 21, 84, 20, 35};
vector<int> res(arr1.size());
// transform(First1, Last1, First2, Result, BinaryOp)
transform(arr1.begin(), arr1.end(), arr2.begin(), res.begin(), multiply);
for (int val : res)
cout << val << " ";
// Output: 54 42 96 260 290 444 147 672 180 350
return 0;
}
การใช้งานกับ Lambda Expressions (C++11 ขึ้นไป)
ในปัจจุบันมักใช้ Lambda แทน Function Pointer เพื่อความกระชับและอ่านง่าย:
// Unary กับ Lambda
transform(v.begin(), v.end(), v.begin(), [](int x){ return x * 2; });
// Binary กับ Lambda
transform(v1.begin(), v1.end(), v2.begin(), v3.begin(),
[](int a, int b){ return a + b; });
ข้อสังเกตสำคัญ
- Destination Range ต้องมีขนาดพอรับผลลัพธ์ (หรือใช้
back_inserter) - Input และ Output Range สามารถทับซ้อนกันได้ (In-place transformation)
- Complexity: Linear - เรียก Operation ทุกครั้งเท่าจำนวน Element
สรุป
std::transform เป็นเครื่องมือที่ทรงพลังสำหรับ Functional Programming ใน C++ ช่วยลด Loop แบบ Manual ให้เป็น Declarative Style ทำให้โค้ดสะอาด อ่านง่าย และลดโอกาสผิดพลาดได้