C++ Standard Library C++ STL Library

C++ set - count() Function



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

Syntax

size_type count (const value_type& val) const;
size_type count (const value_type& val) const;

Parameters

val Specify value to search for.

Return Value

1 if the val is present in the set, else returns 0.

Time Complexity

Logarithmic i.e, Θ(log(n)).

Example:

In the example below, the set::count function is used to check the presence of specified element in the set called MySet.

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

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

The output of the above code will be:

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

❮ C++ <set> Library