Set count() function in C++ STL

This tutorial will discuss about the set count() function in C++ stl.

Table Of Contents

In the C++ Standard Template Library (STL), the set is a container designed to store unique elements in a sorted sequence. The count() member function of the set container is utilized to determine the number of instances of a particular element present in the set.

Syntax of set::count() Function

size_type count(const value_type& value) const;

Parameters:
– value: This is the value of the element that we want to count in the set. The type of this parameter is value_type, which corresponds to the data type of the elements stored in the set.

Return Value:
– Returns 1 if the element is found in the set.
– Returns 0 if the element is not found in the set.

The set class provides a function named count(), which accepts a value as an argument and returns the occurrence count of that value in the set. Since a set contains only unique elements, if the value exists in the set, the return value will always be 1.

This function can also serve as a means to check if an element exists in the set or not. If the return value is 1, it indicates the value exists in the set. Conversely, a return value of 0, means the element does not exist in the set.

Example of set::count()

Let’s see the complete example,

#include <iostream>
#include <set>

int main()
{
    std::set<int> numbers = {11, 22, 33, 44, 55};

    std::cout << "Count of 22 in the set: " << numbers.count(20) << "n";

    std::cout << "Count of 60 in the set: " << numbers.count(60) << "n";

    // Get the occurrence count of value 22 in set
    // and also use that to check if element is in set or not
    if (numbers.count(22))
    {
        std::cout << "Element 22 exists in set n";
    }
    else
    {
        std::cout << "Element 22 does not exists in set n";
    }

    return 0;
}

Output

Count of 22 in the set: 0
Count of 60 in the set: 0
Element 22 exists in set

Scenarios for Exceptions and Undefined Behavior with set::count()

Thread Safety: If the set is being accessed from multiple threads, and at least one of them modifies the set while another is performing a count() operation, it might lead to race conditions or undefined behavior. In such scenarios, it’s vital to use synchronization primitives or other concurrency control mechanisms.

Summary

Today, we learned about set count() function in C++ stl.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top