Open In App

How to Find the Frequency of Vector Elements in a Multiset in C++?

Last Updated : 01 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, the frequency of vector elements in a multiset means how many times the particular element of a vector occurs in a multiset. In this article, we will learn how to find the frequency of vector elements in a multiset in C++.

For Example,

Input: 
vector<int>vec = {5, 1, 3, 2, 4};
multiset<int> ms={1, 1, 1, 2, 2, 3, 4, 4, 5, 5, 5, 5};
Output:
Element: 5, Frequency: 4
Element: 1, Frequency: 3
Element: 3, Frequency: 1
Element: 2, Frequency: 2
Element: 4, Frequency: 2

Find Frequency of Vector Elements in a Multiset in C++

To find the frequency of std::vector elements in a std::multiset, iterate through the vector and find the count of each element of a vector in a multiset by using std::multiset::count() method that returns the number of elements matching a specific key.

C++ Program to Find Frequency of Vector Elements Using Multiset

The below program demonstrates how we can use multiset::count() function to find the frequency of vector elements in a multiset in C++.

C++
// C++ program to find frequency of vector elements in
// multiset
#include <iostream>
#include <set>
#include <vector>
using namespace std;

int main()
{
    // creating vector and multiset
    vector<int> myVector = { 5, 1, 3, 2, 4 };

    multiset<int> myMultiset
        = { 1, 1, 1, 2, 2, 3, 4, 4, 5, 5, 5, 5 };

    // Finding and printing the frequency of vector elements
    // in the multiset
    for (int elem : myVector) {
        int count = myMultiset.count(elem);
        cout << "Element: " << elem << ", "
             << "Frequency: " << count << endl;
    }

    return 0;
}

Output
Element: 5, Frequency: 4
Element: 1, Frequency: 3
Element: 3, Frequency: 1
Element: 2, Frequency: 2
Element: 4, Frequency: 2

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

Note: The above approach works well when the vector doesn't contain duplicates and for vector containing duplicates convert the vector to a set first to filter out duplicates.




Next Article
Practice Tags :

Similar Reads