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

ลบสมาชิกใน Set โดยระบุค่า (Value) ใน C++

STL set มีเมธอด erase(value) ลบสมาชิกที่มีค่าเท่ากับ value โดยตรง คืนค่าจำนวนที่ลบได้ (0 หรือ 1 เนื่องจาก Set ไม่มีค่าซ้ำ)

ตัวอย่างโค้ด

#include <iostream>
#include <set>
using namespace std;

void dispSet(set myset) {
    for (auto it = myset.begin(); it != myset.end(); ++it)
        cout << ' ' << *it;
    cout << '\n';
}

void deleteUsingValue(set myset, int del_element) {
    cout << "Set before deletion:";
    dispSet(myset);

    myset.erase(del_element); // ลบโดยระบุค่า

    cout << "Set after deleting " << del_element << ":";
    dispSet(myset);
}

int main() {
    set tempSet;
    int arr[] = {10, 20, 30, 50, 60, 80, 90, 100, 120, 200, 500};
    int n = sizeof(arr) / sizeof(arr[0]);

    for (int i = 0; i < n; i++)
        tempSet.insert(arr[i]);

    int del_element = 90;
    deleteUsingValue(tempSet, del_element);

    return 0;
}

ผลลัพธ์

Set before deletion: 10 20 30 50 60 80 90 100 120 200 500
Set after deleting 90: 10 20 30 50 60 80 100 120 200 500

รูปแบบ erase() อื่นๆ

// ลบโดย Iterator
myset.erase(myset.find(90));

// ลบช่วง [first, last)
myset.erase(myset.begin(), myset.find(100)); // ลบค่าน้อยกว่า 100