当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。