如何计算整数对多重映射中重复对(具有相同键和值)的数量?
例如,我的多重映射包含对 {(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/