c++ - 如何计算多重映射中重复对的数量

标签 c++ duplicates multimap

如何计算整数对多重映射中重复对(具有相同键和值)的数量?

例如,我的多重映射包含对 {(6,2)、(6,2)、(6,3) 和 (6,4)},因此重复计数为 1,因为我的多重映射中有 1 个重复对多重 map 。我尝试过使用 find() 和 count() 等方法,但无济于事。任何帮助将不胜感激!

最佳答案

一种常见的方法是使用std::set。其中不能包含重复数据。

我们将尝试使用其范围构造函数将所有数据放入 std::set 中。使用 CTAD 使写作变得更容易。

然后我们将 std::multimap 的大小与 std::set 的大小进行比较,并得到所有重复项的数量。

所以它归结为一个非常简单的程序。请参阅:

#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;
}

如果有不同的要求,请反馈,我将创建额外的解决方案。

关于c++ - 如何计算多重映射中重复对的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60342269/

相关文章:

apache - htaccess 重定向以排除某些页面

java - 为什么 it.next() 抛出 java.util.ConcurrentModificationException?

c++ - 在O(1)中用minValue和maxValue实现MinMax PriorityQueue

c++ - 如何通过分隔符标记字符串?

c++ - 如何删除 XML 中的节点及其子节点

Django Inline for ManyToMany 生成重复查询

android - 生成最终存档时出错 : Found duplicate file for APK: res/drawable-ldpi/ic_launcher. png

c++ - 编译器未完成进程

c++ - Flex Lexer 工具中的类 istream

c++ - 基于 C++ 中的值从 HashTable 中删除而不使用 STL