Open In App

How To Find All Occurrences of a Key in a Multimap in C++?

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, multimaps are associative containers similar to maps, but unlike maps, they can store multiple values mapped to the same key. In this article, we will learn how to find all the occurrences of a specific key in a multimap in C++.

Example:

Input:
myMutimap = {{ "id", "111" }, { "id", "112" }, { "student", "John" },
{ "student", "Bob" }, { "student", "Mike" } };

Output:
Occurrences of the key student are:
John Bob Mike

Finding All Values with Given Key in a Multimap in C++

To find all occurrences of a specific key in a multimap in C++ STL, we can use the std::multimap::equal_range() function, which returns a std::pair of iterators representing the range of elements with the specified key in the multimap.

C++ Program for Finding All Values with Given Key in a Multimap

The below program demonstrates how we can find all occurrences of a specific key in a multimap in C++ STL.

C++
// C++ Program to illustrate how to find all the occurrences
// of a specific key in a multimap
#include <iostream>
#include <map>
using namespace std;

int main()
{
    // Creating a multimap
    multimap<string, string> mp
        = { { "id", "111" },        { "id", "112" },
            { "student", "John" },  { "student", "Bob" },
            { "student", "Alice" }, { "student", "Mike" } };

    // Finding all occurrences of a specific key
    string key = "student";
    auto range = mp.equal_range(key);

    // Printing all occurrences of the specific key
    cout << "Occurrences of the  key '" << key
         << "' are: " << endl;
    for (auto it = range.first; it != range.second; ++it) {
        cout << it->second << " ";
    }

    return 0;
}

Output
Occurrences of the  key 'student' are: 
John Bob Alice Mike 

Time Complexity: O(log N), where N is the size of the multiset.
Auxiliary Space: O(1)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads