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

ฟังก์ชัน multiset::clear() ใน C++ STL

ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน multiset::clear() ใน C++ STL

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

Multisets เป็นคอนเทนเนอร์ที่คล้ายกับ set คือเก็บค่าในรูปแบบ key เหมือน set ในลำดับเฉพาะ

ความแตกต่างหลักคือ set มี key แบบ distinct (ไม่ซ้ำ) ส่วน multiset สามารถมี key ซ้ำได้

multiset::clear() คืออะไร?

ฟังก์ชัน multiset::clear() เป็นฟังก์ชันในตัวของ C++ STL อยู่ใน header <set>

ใช้ล้างคอนเทนเนอร์ multiset ทั้งหมด

clear() ลบองค์ประกอบทั้งหมดออกจาก multiset ทำให้ขนาดเป็น 0

ไวยากรณ์

ms_name.clear();

พารามิเตอร์

ฟังก์ชันไม่รับพารามิเตอร์

ค่าที่คืน

ฟังก์ชันนี้ไม่คืนค่า (void)

ตัวอย่าง

Input: std::multiset<int> mymultiset = {1, 2, 2, 3, 4}; mymultiset.clear(); mymultiset.size(); Output: size of multiset = 0

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

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

int main() {
    int arr[] = {2, 4, 1, 3, 8, 5, 6};
    multiset<int> check(arr, arr + 7);
    cout << "List is : ";
    for(auto i = check.begin(); i != check.end(); i++)
        cout << *i << " ";
    cout << "\nList when clear() is applied: ";
    check.clear();
    for(auto i = check.begin(); i != check.end(); i++)
        cout << *i << " ";
    return 0;
}

เอาต์พุต

List is : 1 2 3 4 5 6 8
List when clear() is applied:

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

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

int main() {
    int arr[] = {2, 4, 1, 3, 8, 5, 6};
    multiset<int> check(arr, arr + 7);
    cout << "List is : ";
    for(auto i = check.begin(); i != check.end(); i++)
        cout << *i << " ";
    
    cout << "\nList when clear() is applied: ";
    if(check.empty()) {
        cout << "\nList is null";
    } else {
        cout << "\nList isn't null : ";
        for(auto i = check.begin(); i != check.end(); i++)
            cout << *i << " ";
        cout << "\nsize is : " << check.size();
    }
    
    int arr2[] = {2, 4, 1, 3, 8, 5, 6};
    multiset<int> check_2(arr2, arr2 + 7);
    cout << "\nList when clear() is applied: ";
    check_2.clear();
    if(check_2.empty()) {
        cout << "\nList is null";
        cout << "\nsize is : " << check_2.size();
    } else {
        cout << "\nList isn't null : " << check_2.size();
        for(auto i = check_2.begin(); i != check_2.end(); i++)
            cout << *i << " ";
        cout << "\nsize is : " << check_2.size();
    }
    return 0;
}

เอาต์พุต

List is : 1 2 3 4 5 6 8
List when clear() is applied:
List isn't null : 1 2 3 4 5 6 8
Size is : 7
List when clear() is applied:
List is null
size is : 0