ฟังก์ชัน forward_list::remove() และ remove_if() ใน C++ STL
Forward List ใน STL คืออะไร?
Forward list เป็น sequence container ที่รองรับ insert/erase แบบ constant time ใดๆ ในลำดับ implemented เป็น singly-linked list เก็บ pointer ไปยัง next element เท่านั้น (ไม่มี prev)
forward_list::remove()
ลบองค์ประกอบ ทุกตัว ที่มีค่าเท่ากับค่าที่กำหนด
Syntax
flist.remove(const value_type& value);
พารามิเตอร์
ค่าที่ต้องการลบ
คืนค่า
void
ตัวอย่าง
#include <forward_list>
#include <iostream>
using namespace std;
int main() {
forward_list<int> forwardList = {2, 3, 1, 1, 1, 6, 7};
cout << "list before applying remove operation: ";
for (auto i = forwardList.begin(); i != forwardList.end(); ++i)
cout << ' ' << *i;
forwardList.remove(1); // ลบ 1 ทุกตัว
cout << "\nlist after applying remove operation: ";
for (auto i = forwardList.begin(); i != forwardList.end(); ++i)
cout << ' ' << *i;
return 0;
}
Output: before: 2 3 1 1 1 6 7 → after: 2 3 6 7
forward_list::remove_if()
ลบองค์ประกอบที่ satisfy predicate (condition)
Syntax
flist.remove_if(Predicate pred);
ตัวอย่าง
forward_list<int> fl = {1, 2, 3, 4, 5, 6};
fl.remove_if([](int x) { return x % 2 == 0; }); // ลบเลขคู่
// ผลลัพธ์: 1 3 5
ข้อสังเกต
- แตกต่างจาก
erase()ที่ลบโดย iterator,remove()ลบโดยค่า - ไม่มี
remove()ใน vector/deque (ต้องใช้ erase-remove idiom) - Complexity: O(n) ตรวจสอบทุกโหนด