บทนำ
งานนี้แสดงการทำงานของ forward_list::emplace_after() และ forward_list::emplace_front() ใน C++
forward_list เก็บลิงก์เฉพาะกับอิลิเมนต์ถัดไป ไม่เหมือน list ธรรมดาที่เก็บลิงก์ทั้งถัดไปและก่อนหน้า ซึ่งช่วยให้วนลูปได้ 2 ทิศทาง แต่ forward_list วนลูปได้เฉพาะทิศทางหน้า (Forward) เท่านั้น
ฟังก์ชันทั้งสองเป็นส่วนหนึ่งของ C++ Standard Library
forward_list::emplace_after()ใช้แทรกอิลิเมนต์ใหม่เข้าไปในลิสต์ หลังอิลิเมนต์ที่ตำแหน่งระบุในอาร์กิวเมนต์forward_list::emplace_front()ใช้แทรกอิลิเมนต์ที่จุดเริ่มต้นของลิสต์
ต้อง include <forward_list> ก่อนเรียกใช้
forward_list::emplace_after()
Syntax
Forward_List_Name.emplace_after(iterator, element);
Parameters
- Iterator - Iterator ที่มีตำแหน่งที่จะวางอิลิเมนต์ใหม่
- Element - อิลิเมนต์ที่จะวาง
Return Value
คืนค่า Iterator ที่ชี้ไปที่อิลิเมนต์ใหม่ที่วางเข้าไป
forward_list::emplace_front()
Syntax
Forward_List_Name.emplace_front(element);
Parameters
รับพารามิเตอร์ 1 ตัว (อิลิเมนต์ที่จะแทรกหน้า)
Return Value
ไม่คืนค่า
ตัวอย่าง
Input: 11, 34, 56 Output: 41 11 34 56
คำอธิบาย - สร้าง forward list Lt = {11, 34, 56} เรียก emplace_front(41) แทรก 41 ไปหน้าสุด ผลลัพธ์: 41 11 34 56
แนวทางในโปรแกรม
- สร้างลิสต์ Lt ประเภท int กำหนดค่าเริ่มต้น
- เรียก emplace_front() วางอิลิเมนต์ใหม่หน้าสุด
- สร้าง iterator itr = Lt.end() สำหรับตำแหน่งท้าย
- เรียก emplace_after(itr, element) วางอิลิเมนต์หลังตำแหน่งที่ iterator ชี้
อัลกอริทึม
Start
Step 1 → In main()
Initialize forward_list<int> Lt = {}
Call Lt.emplace_front()
Initialize auto itr = Lt.end()
Call Lt.emplace_after(itr, element)
End
Stop
ตัวอย่างโค้ด
#include <iostream>
#include <forward_list>
using namespace std;
int main() {
forward_list<int> Lt = { 5, 6, 7, 8 };
// ใช้ emplace_front() วางอิลิเมนต์หน้าสุด
Lt.emplace_front(3);
auto itr = Lt.end();
// ใช้ emplace_after() วางอิลิเมนต์หลังตำแหน่งที่ระบุ
Lt.emplace_after(itr, 10);
// แสดงลิสต์
for (auto itr = Lt.begin(); itr != Lt.end(); itr++)
cout << *itr << " ";
return 0;
}
ผลลัพธ์
3 5 6 7 8 10
หมายเหตุ
ในโค้ดต้นฉบับมีข้อผิดพลาดเล็กน้อย: itr != Lt.end ควรเป็น itr != Lt.end() และ cout<<” *itr ”<<” ”; ควรเป็น cout << *itr << " "; โค้ดข้างบนได้แก้ไขแล้ว