當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ unordered_multimap count()用法及代碼示例


unordered_multimap::count()是C++ STL中的內置函數,該函數返回容器中鍵等於該參數中傳遞的鍵的元素數。

用法:

unordered_multimap_name.count(key)

參數:該函數接受單個強製性參數鍵,該鍵指定了要返回其在unordered_multimap容器中的計數的鍵。


返回值:它返回一個無符號整數類型,該整數類型表示 key 在容器中出現的次數。

以下示例程序旨在說明上述函數:

示例1:

// C++ program to illustrate the 
// unordered_multimap::count() 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
  
    // declaration 
    unordered_multimap<int, int> sample; 
  
    // inserts key and element 
    sample.insert({ 10, 100 }); 
    sample.insert({ 10, 100 }); 
    sample.insert({ 20, 200 }); 
    sample.insert({ 30, 300 }); 
    sample.insert({ 30, 150 }); 
  
    cout << "10 occurs " << sample.count(10)  
         << " times"; 
  
    cout << "\n20 occurs " << sample.count(20)  
         << " times"; 
  
    cout << "\n13 occurs " << sample.count(13)  
         << " times"; 
  
    cout << "\n30 occurs " << sample.count(30)  
         << " times"; 
  
    return 0; 
}
輸出:
10 occurs 2 times
20 occurs 1 times
13 occurs 0 times
30 occurs 2 times

示例2:

// C++ program to illustrate the 
// unordered_multimap::count() 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
  
    // declaration 
    unordered_multimap<char, char> sample; 
  
    // inserts key and element 
    sample.insert({ 'a', 'b' }); 
    sample.insert({ 'a', 'b' }); 
    sample.insert({ 'b', 'c' }); 
    sample.insert({ 'r', 'a' }); 
    sample.insert({ 'r', 'b' }); 
  
    cout << "a occurs " << sample.count('a')  
         << " times"; 
  
    cout << "\nb occurs " << sample.count('b')  
         << " times"; 
  
    cout << "\nz occurs " << sample.count('z')  
         << " times"; 
  
    cout << "\nr occurs " << sample.count('r')  
         << " times"; 
  
    return 0; 
}
輸出:
a occurs 2 times
b occurs 1 times
z occurs 0 times
r occurs 2 times


相關用法


注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 unordered_multimap count() function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。