ฟังก์ชัน list::pop_back() ใน C++ STL
List ใน STL คืออะไร?
List คือโครงสร้างข้อมูลที่รองรับการแทรก/ลบที่ตำแหน่งไหนก็ได้ในเวลาคงที่ (O(1)) implemented เป็น doubly linked list จองหน่วยความจำแบบไม่ต่อเนื่อง เข้าถึงโดยตรงช้ากว่า vector/deque
list::pop_back()
ลบองค์ประกอบตัวสุดท้ายของ list container ขนาดลดลง 1
Syntax
list_container.pop_back();
พารามิเตอร์
ไม่มี
คืนค่า
void
ตัวอย่าง 1: ลบองค์ประกอบท้าย
#include <bits/stdc++.h>
using namespace std;
int main() {
list<int> myList;
myList.push_back(4);
myList.push_back(9);
myList.push_back(1);
myList.push_back(3);
cout << "list elements before deletion: ";
for (auto i = myList.begin(); i != myList.end(); i++)
cout << *i << " ";
myList.pop_back(); // ลบ 3
cout << "\nList after deleting element from the end: ";
for (auto i = myList.begin(); i != myList.end(); i++)
cout << *i << " ";
return 0;
}
Output: list elements before deletion: 4 9 1 3 → List after deleting element from the end: 4 9 1
ตัวอย่าง 2: ลบซ้ำจนหมดพร้อมคำนวณผลคูณ
#include <bits/stdc++.h>
using namespace std;
int main() {
list<int> myList;
int product = 1;
myList.push_back(40);
myList.push_back(20);
myList.push_back(30);
while (!myList.empty()) {
product *= myList.back();
myList.pop_back();
}
cout << "The product of elements in my list: " << product << '\n';
return 0;
}
Output: The product of elements in my list: 24000
ฟังก์ชันที่เกี่ยวข้อง
pop_front()- ลบตัวแรกback()- เข้าถึงตัวสุดท้าย (ไม่ลบ)clear()- ลบทั้งหมด