ในบทความนี้ เราจะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::clear() ใน C++ STL
Map ใน C++ STL คืออะไร?
Map เป็น Associative Container ที่เก็บข้อมูลเป็นคู่ Key-Value จัดเรียงตาม Key อัตโนมัติ Key ต้องไม่ซ้ำกัน
map::clear() คืออะไร?
map::clear() ใช้ลบ Element ทั้งหมดออกจาก Map ทำให้ขนาดเป็น 0
Syntax
map_name.clear();
Parameters
ไม่มีพารามิเตอร์
Return Value
ไม่มีค่าคืน (void)
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, string> TP_1, TP_2;
// Insert values
TP_1[1] = "Tutorials";
TP_1[2] = "Point";
TP_1[3] = "is an";
TP_1[4] = "education portal";
// Size before clear
cout << "Map size before clear() function: \n";
cout << "Size of map1 = " << TP_1.size() << endl;
cout << "Size of map2 = " << TP_2.size() << endl;
// Clear both maps
TP_1.clear();
TP_2.clear();
// Size after clear
cout << "Map size after applying clear() function: \n";
cout << "Size of map1 = " << TP_1.size() << endl;
cout << "Size of map2 = " << TP_2.size() << endl;
return 0;
}
ผลลัพธ์
Map size before clear() function: Size of map1 = 4 Size of map2 = 0 Map size after applying clear() function: Size of map1 = 0 Size of map2 = 0
สรุป
clear() ลบข้อมูลทั้งหมดใน Map ทำให้ Map ว่างเปล่า (size = 0) ใช้เมื่อต้องการ Reset Map ให้เริ่มต้นใหม่