ในบทเรียนนี้ เราจะอธิบาย Output Iterators ใน C++
Iterator 5 ประเภท
- Input Iterator
- Output Iterator
- Forward Iterator
- Bidirectional Iterator
- Random Access Iterator
Output Iterator คืออะไร?
Output Iterator ใช้ เขียนค่า (Write-only) ไม่สามารถอ่านค่าได้ ทำงานตรงข้าม Input Iterator
ใช้กับ Algorithm ที่ Output ผลลัพธ์ เช่น copy, fill, transform
ตัวอย่าง
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v1 = {1, 2, 3, 4, 5};
vector<int> v2(5);
// copy ใช้ Output Iterator ของ v2
copy(v1.begin(), v1.end(), v2.begin());
// fill ใช้ Output Iterator
fill(v2.begin(), v2.end(), 0);
// ostream_iterator เป็น Output Iterator
copy(v1.begin(), v1.end(), ostream_iterator<int>(cout, " "));
return 0;
}
ผลลัพธ์
1 2 3 4 5
คุณสมบัติ
- Dereference (*it) = ได้ L-value สำหรับ Assignment
- Increment (++it) = ขยับไปตัวถัดไป
- ไม่สามารถ อ่านค่า (*it เพื่ออ่าน) หรือเปรียบเทียบได้
- Single-pass เท่านั้น