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

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

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

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

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

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

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

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

ฟังก์ชันนี้นับจำนวนองค์ประกอบที่มี key เฉพาะที่ระบุ

Multiset สามารถมีค่าเดียวกันหลายค่าได้ ดังนั้นเมื่อต้องการนับจำนวนค่าของ key เดียวกัน ใช้ count()

ไวยากรณ์

ms_name.count(value_type T);

พารามิเตอร์

ฟังก์ชันรับพารามิเตอร์ 1 ตัว คือค่าที่ต้องการค้นหาใน multiset

ค่าที่คืน

คืนจำนวนค่าที่มี key เดียวกัน หากไม่มี key ที่ค้นหา คืน 0

ตัวอย่าง

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

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

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

int main() {
    int arr[] = {1, 2, 3, 1, 1, 1};
    multiset<int> check(arr, arr + 6);
    cout << "List is : ";
    for(auto i = check.begin(); i != check.end(); i++)
        cout << *i << " ";
    cout << "\n1 is occuring: " << check.count(1) << " times";
    return 0;
}

เอาต์พุต

List is : 1 1 1 1 2 3
1 is occuring 4 times

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

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

int main() {
    int arr[] = {1, 2, 3, 1, 1, 1, 2, 2};
    multiset<int> check(arr, arr + 8);
    cout << "List is : ";
    for(auto i = check.begin(); i != check.end(); i++)
        cout << *i << " ";
    cout << "\n1 is occuring: " << check.count(1) << " times";
    cout << "\n2 is occuring: " << check.count(2) << " times";
    return 0;
}

เอาต์พุต

List is : 1 1 1 1 2 2 2 3
1 is occuring 4 times
2 is occuring 3 times