ในบทความนี้เราจะอภิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน list::clear() ใน C++
List ใน STL คืออะไร?
List เป็นโครงสร้างข้อมูลที่อนุญาตให้แทรกและลบได้ในเวลาคงที่ที่ตำแหน่งใดก็ตามในลำดับ List ถูกนำไปใช้เป็น doubly linked lists List อนุญาตการจัดสรรหน่วยความจำแบบไม่ต่อเนื่อง List ทำงานการแทรก ดึง และย้ายองค์ประกอบได้ดีกว่า array, vector และ deque ใน List การเข้าถึงองค์ประกอบโดยตรงช้า และ list คล้ายกับ forward_list แต่วัตถุ forward_list เป็น singly linked lists และสามารถวนรอบได้เฉพาะไปข้างหน้า
clear() คืออะไร?
list::clear() เป็นฟังก์ชันในตัวใน C++ STL ซึ่งประกาศในไฟล์หัวเรื่อง list::clear() ล้างรายการทั้งหมด กล่าวอีกนัยหนึ่ง clear() ลบองค์ประกอบทั้งหมดที่อยู่ในคอนเทนเนอร์ list และทิ้งคอนเทนเนอร์ไว้ขนาด 0
ไวยากรณ์
list_name.clear();
ฟังก์ชันนี้ไม่รับพารามิเตอร์
ค่าที่คืน
ฟังก์ชันนี้ไม่คืนค่าอะไร แค่ลบองค์ประกอบทั้งหมดออกจากคอนเทนเนอร์
ตัวอย่าง
ในโค้ดด้านล่างเราจะแทรกองค์ประกอบลงใน list และหลังจากนั้นเราจะใช้ฟังก์ชัน clear เพื่อล้างรายการทั้งหมดทำให้ว่างเปล่า
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> myList = { 10, 20, 30, 40, 50 };
cout << "List before applying clear() function: ";
for (auto i = myList.begin(); i != myList.end(); ++i)
cout << ' ' << *i;
// applying clear() function to clear the list
myList.clear();
for (auto i = myList.begin(); i != myList.end(); ++i)
cout << ' ' << *i;
cout << "\nlist is cleared";
return 0;
}เอาต์พุต
List before applying clear() function 10 20 30 40 50 list is cleared
ตัวอย่างที่ 2
ในโค้ดด้านล่างเราจะล้างรายการทั้งหมดด้วย clear() และหลังจากนั้นแทรกองค์ประกอบใหม่และแสดงผล
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> myList;
list<int>::iterator i;
myList.push_back(10);
myList.push_back(20);
myList.push_back(30);
cout << "List before applying clear() function: ";
for (auto i = myList.begin(); i != myList.end(); ++i)
cout << ' ' << *i;
myList.clear();
for (auto i = myList.begin(); i != myList.end(); ++i)
cout << ' ' << *i;
cout << "\nlist is cleared";
myList.push_back(60);
myList.push_back(70);
cout << "\nelements in my list are: ";
for (auto i = myList.begin(); i != myList.end(); ++i)
cout << ' ' << *i;
return 0;
}เอาต์พุต
List before applying clear() function 10 20 30 40 50 list is cleared Elements in my list are: 60 70