ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน list::push_front() และ list::push_back() ใน C++ STL
List ใน STL คืออะไร?
List เป็นโครงสร้างข้อมูลที่รองรับการแทรกและลบ (insertion/deletion) ในเวลาคงที่ทุกตำแหน่งในลำดับ List ถูกนำไปใช้งานเป็น doubly linked list รองรับการจัดสรรหน่วยความจำที่ไม่ต่อเนื่อง (non-contiguous) List ทำการแทรก ดึง และย้ายองค์ประกอบได้ดีกว่า array, vector และ deque แตการเข้าถึงโดยตรง (random access) ช้ากว่า
list::push_front() คืออะไร?
list::push_front() เป็นฟังก์ชันในตัวใน C++ STL ประกาศใน <list> ใช้เพื่อแทรกองค์ประกอบที่ด้านหน้า (front) ของ list container การแทรกทำให้องค์ประกอบแรกเดิมกลายเป็นองค์ประกอบที่สอง และขนาด list เพิ่มขึ้น 1
ไวยากรณ์
list_container1.push_front(type_t& value);
พารามิเตอร์
ฟังก์ชันนี้รับพารามิเตอร์หนึ่งคือค่าที่ต้องการแทรกที่ด้านหน้า
ค่าที่คืน
ฟังก์ชันนี้ไม่คืนค่าอะไร
ตัวอย่าง
Input: list<int> List_container = {10, 11, 13, 15}; List_container.push_front(9);
Output: List = 9 10 11 13 15
ตัวอย่างโค้ด
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> myList{};
myList.push_front(10);
myList.push_front(20);
myList.push_front(30);
myList.push_front(40);
myList.push_front(50);
myList.sort();
cout << "Elements in the list are : ";
for (auto i = myList.begin(); i != myList.end(); ++i)
cout << ' ' << *i;
}
เอาต์พุต
Elements in the list are : 10 20 30 40 50
list::push_back() คืออะไร?
list::push_back() เป็นฟังก์ชันในตัวใน C++ STL ประกาศใน <list> ใช้เพื่อแทรกองค์ประกอบที่ด้านหลัง (back) ของ list container การแทรกทำให้องค์ประกอบสุดท้ายเดิมกลายเป็นองค์ประกอบลำดับสองจากท้าย และขนาด list เพิ่มขึ้น 1
ไวยากรณ์
list_container1.push_back(type_t& value);
พารามิเตอร์
ฟังก์ชันนี้รับพารามิเตอร์หนึ่งคือค่าที่ต้องการแทรกที่ด้านหลัง
ค่าที่คืน
ฟังก์ชันนี้ไม่คืนค่าอะไร
ตัวอย่าง
Input: list<int> List_container = {10, 11, 13, 15}; List_container.push_back(9);
Output: List = 10 11 13 15 9
ตัวอย่างโค้ด
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> myList{};
myList.push_back(10);
myList.push_back(20);
myList.push_back(30);
myList.push_back(40);
myList.push_back(50);
myList.sort();
cout << "Elements in the list are : ";
for (auto i = myList.begin(); i != myList.end(); ++i)
cout << ' ' << *i;
}
เอาต์พุต
Elements in the list are : 10 20 30 40 50