Last Updated : 11 Jul, 2025
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;
}
set::count() Syntax
s.count(val);
where, s is the name of std::set container.
ParametersThe 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)
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;
}
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;
}
Set count of 2: 1 Multiset count of 2: 2
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4