ในบทความนี้เราจะอภิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน pop_front() ใน C++
List ใน STL คืออะไร
List เป็นโครงสร้างข้อมูลที่อนุญาตให้แทรกและลบได้ในเวลาคงที่ที่ตำแหน่งใดก็ตามในลำดับ List ถูกนำไปใช้เป็น doubly linked lists List อนุญาตการจัดสรรหน่วยความจำแบบไม่ต่อเนื่อง List ทำงานการแทรก ดึง และย้ายองค์ประกอบได้ดีกว่า array, vector และ deque ใน List การเข้าถึงองค์ประกอบโดยตรงช้า และ list คล้ายกับ forward_list แต่วัตถุ forward_list เป็น singly linked lists และสามารถวนรอบได้เฉพาะไปข้างหน้า
pop_front() คืออะไร
pop_front() เป็นฟังก์ชันในตัวใน C++ STL ซึ่งประกาศในไฟล์หัวเรื่อง pop_front() ใช้ pop (ลบ) องค์ประกอบจากจุดเริ่มต้นของคอนเทนเนอร์ list ฟังก์ชันลบองค์ประกอบแรกของคอนเทนเนอร์ list หมายความว่าองค์ประกอบที่สองจะกลายเป็นองค์ประกอบแรก และองค์ประกอบแรกจะถูกลบออกจากคอนเทนเนอร์ ฟังก์ชันนี้ลดขนาดของคอนเทนเนอร์ลง 1
ไวยากรณ์
void pop_front();
ฟังก์ชันนี้ไม่รับพารามิเตอร์
ค่าที่คืน
ฟังก์ชันนี้ไม่คืนค่าอะไร แค่ลบ/pop องค์ประกอบแรกออกจากคอนเทนเนอร์
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int main() {
// create a list
list<int> myList;
// inserting elements to the list
myList.push_back(1);
myList.push_back(2);
myList.push_back(3);
myList.push_back(4);
// List before applying pop_front() function
cout << "List contains: ";
for(auto i = myList.begin(); i != myList.end(); i++)
cout << *i << " ";
// removing first element using pop_front()
myList.pop_front();
// List after removing element from front
cout << "\nList after removing an element from front: ";
for(auto i = myList.begin(); i != myList.end(); i++)
cout << *i << " ";
return 0;
}เอาต์พุต
List contains: 1 2 3 4 List after removing an element from front: 2 3 4
ตัวอย่างที่ 2
#include <iostream>
#include <list>
int main() {
std::list<int> myList;
myList.push_back(10);
myList.push_back(20);
myList.push_back(30);
std::cout << "removing the elements in a list: ";
while (!myList.empty()) {
std::cout << ' ' << myList.front();
myList.pop_front();
}
std::cout << "\nSize of my empty list is: " << myList.size() << '\n';
return 0;
}เอาต์พุต
removing the elements in a list: 10 20 30 Size of my empty list is: 0