C++ multimap::count() Function



The C++ std::multimap::count() function is used to return the number of elements matching a specified key. Unlike std::map, where each key is unique, std::multimap allows multiple elements with the same key.It operates on a sorted collection where each key can be associated with multiple values. By using this function, we can determine the occurence of a particular key within the multimap. The time complexity of this function is logarithmic i.e.O(log n).

Syntax

Following is the syntax for std::multimap::count() function.

size_type count (const key_type& k) const;

Parameters

  • k − It indicates the key to search for.

Return value

This function returns the number of values associated with key.

Example

In the following example, we are going to demonstrate the basic usage of count() function.

#include 
#include 
int main()
{
    std::multimap a = {{1, "Sail"}, {2, "Audi"}, {1, "Beat"}, {1, "Cruze"}};
    int x = 1;
    int y = a.count(x);
    std::cout << "Occurrences of key " << x << ": " << y << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

Occurrences of key 1: 3

Example

Consider the following example, where we are going to get the count of key that does not exist.

#include 
#include 
int main()
{
    std::multimap a = {{1, "Hi"}, {2, "Hello"},{3, "Namaste"}};
    int x = 5;
    int y = a.count(x);
    std::cout << "Occurrences of key " << x << ": " << y << std::endl;
    return 0;
}

Output

Following is the output of the above code −

Occurrences of key 5: 0

Example

Let's look at the following example, where we are going to apply count on the empty multimap and observe output.

#include 
#include 
int main()
{
    std::multimap x;
    int a = 2;
    int b = x.count(a);
    std::cout << "Occurrences of key " << a << ": " << b << std::endl;
    return 0;
}

Output

If we run the above code it will generate the following output −

Occurrences of key 2: 0

Example

Following is the example, where we are going to use the count() function in the loop.

#include 
#include 
int main()
{
    std::multimap a = {{1, "Hi"}, {1, "Hello"}, {3, "Welcome"}};
    for (int x = 1; x <= 2; ++x) {
        int y = a.count(x);
        std::cout << "Occurrences of key " << x << " : " << y << std::endl;
    }
    return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

Occurrences of key 1 : 2
Occurrences of key 2 : 0
multimap.htm
Advertisements