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


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


unordered_set::count()函數是C++ STL中的內置函數,用於對unordered_set容器中特定元素的出現進行計數。由於unordered_set容器不允許存儲重複的元素,因此該函數通常用於檢查容器中是否存在元素。如果元素存在於容器中,則該函數返回1,否則返回0。

用法

unordered_set_name.count(element)

參數:此函數接受單個參數element 。此參數表示容器中是否存在需要檢查的元素。


返回值:如果元素存在於容器中,則此函數返回1,否則返回0。

以下示例程序旨在說明unordered_set::count()函數:

示例1:

// CPP program to illustrate the 
// unordered_set::count() function 
  
#include <iostream> 
#include <unordered_set> 
  
using namespace std; 
  
int main() 
{ 
  
    unordered_set<int> sampleSet; 
  
    // Inserting elements 
    sampleSet.insert(5); 
    sampleSet.insert(10); 
    sampleSet.insert(15); 
    sampleSet.insert(20); 
    sampleSet.insert(25); 
  
    // displaying all elements of sampleSet 
    cout << "sampleSet contains: "; 
    for (auto itr = sampleSet.begin(); itr != sampleSet.end(); itr++) { 
        cout << *itr << " "; 
    } 
  
    // checking if element 20 is present in the set 
    if (sampleSet.count(20) == 1) { 
        cout << "\nElement 20 is present in the set"; 
    } 
    else { 
        cout << "\nElement 20 is not present in the set"; 
    } 
  
    return 0; 
}
輸出:
sampleSet contains: 25 5 10 15 20 
Element 20 is present in the set

示例2:

// C++ program to illustrate the 
// unordered_set::count() function 
  
#include <iostream> 
#include <unordered_set> 
  
using namespace std; 
  
int main() 
{ 
  
    unordered_set<string> sampleSet; 
  
    // Inserting elements 
    sampleSet.insert("Welcome"); 
    sampleSet.insert("To"); 
    sampleSet.insert("GeeksforGeeks"); 
    sampleSet.insert("Computer Science Portal"); 
    sampleSet.insert("For Geeks"); 
  
    // displaying all elements of sampleSet 
    cout << "sampleSet contains: "; 
    for (auto itr = sampleSet.begin(); itr != sampleSet.end(); itr++) { 
        cout << *itr << " "; 
    } 
  
    // checking if element GeeksforGeeks is 
    // present in the set 
    if (sampleSet.count("GeeksforGeeks") == 1) { 
        cout << "\nGeeksforGeeks is present in the set"; 
    } 
    else { 
        cout << "\nGeeksforGeeks is not present in the set"; 
    } 
  
    return 0; 
}
輸出:
sampleSet contains: Welcome To GeeksforGeeks For Geeks Computer Science Portal 
GeeksforGeeks is present in the set


相關用法


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