在数组中使用C++中的哈希表复制数组中的元素

Duplicate elements in array using Hash Table in C++

本文关键字:哈希表 复制数组 元素 数组 C++      更新时间:2023-10-16

有人可以举一个使用哈希表和函数查找数组重复项的示例吗?

我正在寻找C++的一些例子。我得到的代码都是Java的。

一种解决方案是将数组的元素(作为键(及其出现次数(作为值(放入哈希表中。然后,复制关联值大于 1 的哈希表的键。

#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <algorithm>
int main(int argc, char* argv[]) {
    std::vector<int> vec{1,1,2,3,1,4,5};
    std::map<int, int> m;
    // We copy the element of the vector into the hash table
    std::for_each(vec.begin(), vec.end(), [&m](auto & elt){ m[elt] += 1; });
    std::vector<int> res;
    // We select the key where the value is > 1
    std::for_each(m.begin(), m.end(), [&res](auto & elt) { if(elt.second > 1) res.push_back(elt.first); });
}