Open In App

set::count() Function in C++ STL

Last Updated : 22 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The std::set::count() is a built-in function in C++ STL which is used to count the number of times an element occurs in the set container. std::set container stores unique elements, so it can only return 1 or 0. Therefore, it is only used for checking if the element exists in the set or not.

Example

C++
// C++ Program to illustrate the use of
// std::set::count() method
#include <bits/stdc++.h>
using namespace std;

int main() {
    set<int> s = {1, 2, 4, 3, 6};

    // Checking element that exists
    cout << s.count(1) << endl;
  
  	// Checking elements that doesn't exists
    cout << s.count(5);
    return 0;
}

Output
1
0

set::count() Syntax

s.count(val);

where, s is the name of std::set container.

Parameters

  • val: Value whose count is to be determined.

Return Value

  • Returns 1, if the value is present in the set.
  • Returns 0, if the value is not present in the set.

Complexity Analysis

The std::set container is generally implemented by a self-balancing binary search tree. The set::count() function searches for the given value in the set. So, search operation in self-balancing BST,

Time Complexity: O(log n), where n is the number of elements in the set.
Auxiliary Space: O(1)

More Examples of set::count()

The following examples illustrates the use of set::count() function:

Example 1: Checking Element Existence Using set::count()

C++
// C++ Program to check element existance
// using std::set::count()
#include <bits/stdc++.h>
using namespace std;

int main() {
    set<int> s = {1, 2, 4};
    
    // Checking element that exists
    if (s.count(3))
        cout << "Exists";
    else
        cout << "Not exists";
    return 0;
}

Output
Not exists

Example 2: Comparing set::count() with multiset::count()

C++
// C++ Program to compare std::set::count()
// with std::multiset::count()
#include <bits/stdc++.h>
using namespace std;

int main() {
    set<int> s = {1, 2, 2, 4};
    multiset<int> ms = {1, 2, 2, 4};

    // Counting the occurences of 2 in both
  	// set and multiset
    cout << "Set count of 2: " << s.count(2)
      << endl;
    cout << "Multiset count of 2: " <<
      ms.count(2);
    return 0;
}

Output
Set count of 2: 1
Multiset count of 2: 2


Next Article
Practice Tags :

Similar Reads