Get Value Count in MultiSet in C++

This tutorial will discuss how to get occurrence count of a value in multiset in C++?.

Multiset in C++ provides a member function called ‘count()’, which accepts a value as an argument and returns the occurrence count of that value in the multiset.

Unlike a set, a multiset can hold duplicate values. Therefore, if we pass a value to the ‘count()’ function and there are duplicate entries of that value in the multiset, it will return its occurrence count.

Let’s understand this with an example: Suppose we have a multiset of integers like this,

std::multiset<int> numSet{11, 22, 33, 44, 33, 44, 33, 55, 66, 77, 88};

We are looking for the occurrence count of the value ’33’ in the set.

std::size_t occurrenceCount = numSet.count(33);

std::cout<< "Occuurrence Count of value 33 is: "
        << occurrenceCount
        << std::endl;

Output:

Occuurrence Count of value 33 is: 3

It will return 3 because the value ’33’ occurs three times in the multiset.



    Let’s consider another example. Here, we will try to fetch the occurrence count of the value ’55’ in the multiset.

    occurrenceCount = numSet.count(55);
    
    std::cout<< "Occuurrence Count of value 55 is: "
                << occurrenceCount
                << std::endl;
    

    Output:

    Occuurrence Count of value 55 is: 0
    

    Since the value ’55’ does not exist in the multiset, it will return 0.

    Let’s see the complete example,

    #include <iostream>
    #include <set>
    
    int main()
    {
        std::multiset<int> numSet{11, 22, 33, 44, 33, 44, 33, 55, 66, 77, 88};
    
        std::size_t occurrenceCount = numSet.count(33);
    
        std::cout<< "Occuurrence Count of value 33 is: "
                 << occurrenceCount
                 << std::endl;
    
    
        occurrenceCount = numSet.count(55);
    
        std::cout<< "Occuurrence Count of value 55 is: "
                 << occurrenceCount
                 << std::endl;
    
        return 0;
    }
    

    Output

    Occuurrence Count of value 33 is: 3
    Occuurrence Count of value 55 is: 1
    

    Summary

    Today, we learned how to get occurrence count of a value in multiset in C++?.

    Scroll to Top