set count() function in C++ STL - GeeksforGeeks (2024)

Last Updated : 05 Jun, 2023

Improve

The set::count() is a built-in function in C++ STL which returns the number of times an element occurs in the set. It can only return 1 or 0 as the set container contains unique elements only.

Syntax

The syntax of set::count is:

set_name.count (element); 

Parameters

  • The function accepts one mandatory parameter element which specifies the element whose count is to be returned.

Return Value

The function returns 1 or 0 as the set contains unique elements only.

  • It returns 1 if the value is present in the set container.
  • It returns 0 if it is not present in the container.

Complexity Analysis

  • Time Complexity: O(log N), where N is the number of elements present in the set.
  • Space Complexity: O(1)

Example

The below C++ program demonstrates the use of the count() function in the set container.

C++

// CPP program to demonstrate the

// set::count() function

#include <bits/stdc++.h>

using namespace std;

int main()

{

int arr[] = { 14, 12, 15, 11, 10 };

// initializes the set from an array

set<int> s(arr, arr + 5);

// check if 11 is present or not

if (s.count(11))

cout << "11 is present in the set\n";

else

cout << "11 is not present in the set\n";

// checks if 18 is present or not

if (s.count(18))

cout << "18 is present in the set\n";

else

cout << "18 is not present in the set\n";

return 0;

}

Output

11 is present in the set18 is not present in the set

Difference between count() and find()

The difference between count() and find() functions in a set is count() returns 0 or 1 depending upon whether the element is not present or present respectively whereas the find() function returns an iterator pointing to the value if present else next to the last value in the set.


Like Article

Suggest improvement

Share your thoughts in the comments

Please Login to comment...

set count() function in C++ STL - GeeksforGeeks (2024)
Top Articles
Latest Posts
Article information

Author: Jamar Nader

Last Updated:

Views: 5721

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Jamar Nader

Birthday: 1995-02-28

Address: Apt. 536 6162 Reichel Greens, Port Zackaryside, CT 22682-9804

Phone: +9958384818317

Job: IT Representative

Hobby: Scrapbooking, Hiking, Hunting, Kite flying, Blacksmithing, Video gaming, Foraging

Introduction: My name is Jamar Nader, I am a fine, shiny, colorful, bright, nice, perfect, curious person who loves writing and wants to share my knowledge and understanding with you.