C++ Standard Library C++ STL Library

C++ unordered_set - count() Function



The C++ unordered_set::count function returns the number of occurrences of an element in the unordered_set container. As an unordered_set contains unique elements, hence the function returns either 1 if the element is present in the unordered_set or 0 otherwise.

Syntax

size_type count (const key_type& k) const;

Parameters

k Specify value to search for.

Return Value

1 if the specified element is present in the unordered_set, else returns 0.

Time Complexity

Average case: Constant i.e, Θ(1).
Worst case: Linear i.e, Θ(n).

Example:

In the example below, the unordered_set::count function is used to check the presence of specified element in uSet.

#include <iostream>
#include <unordered_set>
using namespace std;
 
int main (){
  unordered_set<int> uSet{55, 25, 128, 5, 7};

  for(int i=5; i<10; i++) {
    if(uSet.count(i)==0)
      cout<<i<<" is not an element of uSet.\n";
    else
      cout<<i<<" is an element of uSet.\n";
  }
  return 0;
}

The output of the above code will be:

5 is an element of uSet.
6 is not an element of uSet.
7 is an element of uSet.
8 is not an element of uSet.
9 is not an element of uSet.

❮ C++ <unordered_set> Library