C++ STL 中的 multiset count() 函式


在本文中,我們將討論 C++ STL 中 multiset::count() 函式的工作原理、語法和示例。

什麼是 C++ STL 中的 multiset?

Multiset 與 set 容器類似,這意味著它們以鍵的形式儲存值,就像 set 一樣,以特定的順序儲存。

在 multiset 中,值與 set 一樣被識別為鍵。multiset 和 set 之間的主要區別在於 set 具有不同的鍵,這意味著沒有兩個鍵是相同的,而在 multiset 中可以有相同的鍵值。

Multiset 鍵用於實現二叉搜尋樹。

什麼是 multiset::count()?

multiset::count() 函式是 C++ STL 中的內建函式,它在 <set> 標頭檔案中定義。

此函式計算具有特定鍵的元素的數量。

一個 multiset 可以具有多個相同鍵的值,因此當我們想要計算相同鍵的值的數量時,可以使用 count()。count() 在整個容器中搜索鍵並返回結果。如果容器中沒有我們正在查詢的鍵,則函式返回 0。

語法

ms_name.count(value_type T);

引數

該函式接受一個 multiset 值型別的引數,我們必須在關聯的 multiset 容器中搜索該引數。

返回值

此函式返回具有相同鍵的值的數量。

示例

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

示例

 線上演示

#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

示例

 線上演示

#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

更新於: 2020年3月23日

712 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告