Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน map::erase() ใน C++ STL


ในบทความนี้ เราจะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::erase() ใน C++ STL

Map ใน C++ STL คืออะไร?

Map เป็น Associative Container ที่เก็บข้อมูลเป็นคู่ Key-Value จัดเรียงตาม Key อัตโนมัติ Key ต้องไม่ซ้ำกัน

map::erase() คืออะไร?

map::erase() ใช้ลบ Element ออกจาก Map ตาม Key, Iterator หรือ Range ลดขนาด Container ตามจำนวนที่ลบ

Syntax (3 รูปแบบ)

1. map_name.erase(iterator pos);           // ลบที่ Iterator
2. map_name.erase(key_type &k);             // ลบตาม Key
3. map_name.erase(iterator first, iterator last); // ลบ Range

Parameters

  • pos − Iterator ชี้ Element ที่จะลบ
  • k − Key ที่จะลบ
  • first, last − Range [first, last) ที่จะลบ

Return Value

รูปแบบ Key: คืนจำนวน Element ที่ลบได้ (0 หรือ 1 เนื่องจาก Key Unique)

รูปแบบ Iterator/Range: ไม่มีค่าคืน (void) ใน C++11 เป็นต้นมา คืน Iterator ตัวถัดไป

ตัวอย่าง 1: ลบตาม Key

#include <bits/stdc++.h>
using namespace std;

int main() {
    map<int, int> TP_Map;
    TP_Map.emplace(3, 50);
    TP_Map.emplace(2, 30);
    TP_Map.emplace(1, 10);
    TP_Map.emplace(4, 70);
    
    cout << "TP Map is : \nMAP_KEY\tMAP_ELEMENT\n";
    for (auto i = TP_Map.begin(); i != TP_Map.end(); i++)
        cout << i->first << "\t" << i->second << endl;
    
    TP_Map.erase(1); // ลบ Key 1
    TP_Map.erase(2); // ลบ Key 2
    
    cout << "\nAfter erasing elements: \nMAP_KEY\tMAP_ELEMENT\n";
    for (auto i = TP_Map.begin(); i != TP_Map.end(); i++)
        cout << i->first << "\t" << i->second << endl;
    
    return 0;
}

ผลลัพธ์

TP Map is:
MAP_KEY     MAP_ELEMENT
1           10
2           30
3           50
4           70
After erasing elements:
MAP_KEY     MAP_ELEMENT
3           50
4           70

ตัวอย่าง 2: ลบตาม Iterator (ผ่าน find)

#include <bits/stdc++.h>
using namespace std;

int main() {
    map<int, int> TP_Map;
    TP_Map.insert({3, 50});
    TP_Map.insert({2, 30});
    TP_Map.insert({1, 10});
    TP_Map.insert({4, 70});
    
    auto it1 = TP_Map.find(1);
    TP_Map.erase(it1); // ลบผ่าน Iterator
    
    auto it2 = TP_Map.find(2);
    TP_Map.erase(it2);
    
    // ผลลัพธ์เหมือนตัวอย่าง 1
    return 0;
}

สรุป

  • ลบตาม Key: ใช้ erase(key) สะดวกที่สุด
  • ลบตาม Iterator: ใช้ erase(iterator) เมื่อมี Iterator อยู่แล้ว
  • ลบช่วง: ใช้ erase(first, last)