How to count number of duplicate pairs in multimap

Viewed 306

how can I count the number of duplicate pairs (with same key and value) in a multimap of pairs of integers?

For example, my multimap contains the pairs {(6,2), (6,2), (6,3) and (6,4)} so the duplicate count is 1 as I have 1 duplicate pair in my multimap. I have tried using methods such as find() and count() but to no avail. Any help will be greatly appreciated!

1 Answers

One common approach is to use a std::set. This cannot contain duplicate data.

We will try to put all data into the std::set using its range constructor. Using CTAD makes writing easier.

Then we compare the size of the std::multimap with that of the std::set and have the number of all duplicates.

So it boils down to a very simple program. Please see:

#include <iostream>
#include <map>
#include <set>

int main()
{
    // Source data
    std::multimap<int, int> mm = { {6, 2}, {6, 3}, {6, 2}, {6, 4} };

    // Use range constructor and CTAD to put the data into a set
    std::set s(mm.begin(), mm.end());

    // Show result
    std::cout << "Number of duplicates: " << mm.size() - s.size() << "\n";

    return 0;
}

If there are different requirements, then please feedback and I will create an additional solution.

Related