ในบทความนี้เราจะพูดถึงการทำงาน ไวยากรณ์และตัวอย่างของฟังก์ชัน map::clear() ใน C++ STL
แผนที่ใน C++ STL คืออะไร
แผนที่เป็นคอนเทนเนอร์ที่เชื่อมโยงกัน ซึ่งอำนวยความสะดวกในการจัดเก็บองค์ประกอบที่เกิดขึ้นจากการรวมกันของค่าคีย์และค่าที่แมปในลำดับเฉพาะ ในคอนเทนเนอร์แผนที่ ข้อมูลจะถูกจัดเรียงภายในเสมอโดยใช้คีย์ที่เกี่ยวข้อง ค่าในคอนเทนเนอร์แผนที่สามารถเข้าถึงได้โดยคีย์เฉพาะของมัน
map::clear() คืออะไร
ฟังก์ชัน map::clear() เป็นฟังก์ชัน inbuilt ใน C++ STL ซึ่งกำหนดไว้ในไฟล์ส่วนหัว
ไวยากรณ์
Map_name.clear();
พารามิเตอร์
ฟังก์ชันนี้ไม่รับพารามิเตอร์ใดๆ
คืนค่า
ฟังก์ชันนี้ไม่ส่งคืนสิ่งใด
ตัวอย่าง
อินพุต
map<char, int> newmap; newmap[‘a’] = 1; newmap[‘b’] = 2; newmap[‘c’] = 3; newmap.clear();
ผลลัพธ์
size of the map is: 0
ตัวอย่าง
#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 of map
cout<< "Map size before clear() function: \n";
cout << "Size of map1 = "<<TP_1.size() << endl;
cout << "Size of map2 = "<<TP_2.size() << endl;
//call clear() to delete the elements
TP_1.clear();
TP_2.clear();
//now print the size of maps
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