ฟังก์ชัน list::front() ใน C++ STL
list::front() คืออะไร?
คืน reference ไปยังองค์ประกอบตัวแรกของ list container การใช้กับ empty list จะทำให้เกิด undefined behavior
Syntax
list_container.front();
พารามิเตอร์
ไม่มี
คืนค่า
Reference ไปยังองค์ประกอบตัวแรก (สามารถอ่าน/เขียนได้)
ตัวอย่าง 1: อ่านค่าตัวแรก
#include <bits/stdc++.h>
using namespace std;
int main() {
list<int> myList;
myList.push_back(3);
myList.push_back(2);
myList.push_back(21);
myList.push_back(11);
int first_ele = myList.front();
cout << "first element in a list is: " << first_ele;
return 0;
}
Output: first element in a list is: 3
ตัวอย่าง 2: แทนที่ค่าตัวแรกด้วยค่าตัวสุดท้าย
#include <iostream>
#include <list>
int main() {
std::list<int> myList;
myList.push_back(77);
myList.push_back(2);
myList.push_back(21);
myList.push_back(23);
myList.front() = myList.back(); // แทนที่ 77 ด้วย 23
std::cout << "replacing first element with the last element: "
<< myList.front() << '\n';
return 0;
}
Output: replacing first element with the last element: 23
ฟังก์ชันคู่: list::back()
back()- reference ไปยังองค์ประกอบตัวสุดท้าย- ทั้งคู่เป็น O(1)
- ใช้กับ empty list → undefined behavior
ข้อสังเกต
- แตกต่างจาก
begin()ที่คืน iterator,front()คืน reference โดยตรง - เหมาะสำหรับ stack/queue operations ที่ต้องเข้าถึง head/tail บ่อย
- ใน
forward_listมีแค่front()ไม่มีback()