c++ - 如何检测 unordered_map 向量中的重复项?
问题描述
给定 a vector
,unordered_map<u_int,int>
我想检查 是否vector
包含任何重复值。如果两个 unordered_map 的所有键和对应的值都相等,则认为它们是重复的。我知道比较运算符存在于unordered_maps
,但我想避免每个元素相互之间的成对比较。一种经典的解决方案是将 的值vector
插入 a ,然后比较和set
中的元素数量。但是,这里的问题是要插入的对象必须具有重载的比较运算符。在 的情况下,必须为复杂对象重载要使用的散列函数。为了重载,我需要从set
vector
set
unordered_set
std::unordered_map
. 然后我需要重载比较运算符或哈希函数。我能想到的另一个解决方案是将所有键值对连接成一个字符串,然后按键对字符串进行排序并检测这些字符串上的重复项。我想知道这个问题的最佳解决方案是什么。
示例数据:
using namespace std;
typedef unordered_map<u_int,int> int_map;
int_map a = { {1,1}, {2,4}, {3,5} };
int_map b = { {1,1}, {2,-1}, {4,-2} };
int_map c = { {1,1}, {3,5} };
vector<unordered_map<u_int,int>> my_vec;
my_vec.push_back(a);
my_vec.push_back(b);
my_vec.push_back(c);
的内容my_vec
是:
{ { 1 => 1, 2 => 4, 3 => 5 },
{ 1 => 1, 2 => -1, 4 => -2 },
{ 1 => 1, 3 => 5 } }
如果问题不够清楚,请随时询问/评论/编辑。任何帮助,将不胜感激。先感谢您!
解决方案
您可以类似于以下内容:
typedef unordered_map<u_int,int> int_map;
struct my_map_comparator
{
bool operator()(const int_map& a, const int_map& b)
{
a_hash = compute_hash_for_a(all keys of a)
b_hash = compute_hash_for_b(all keys of b)
return a_hash == b_hash;
}
};
std::unordered_set<int_map,std::hash<int_map>, my_map_comparator> map_list();
推荐阅读
- ruby-on-rails - 如何在 Rails 迁移中设置排序规则
- pandas - 读取引用中的变量以进行计数
- python - 用于合并三个排序列表的递归 Python 程序
- java - API路由配置问题
- python - 为什么我不能在 Python 上单击并拖动圆圈?
- woocommerce - 如何将添加到购物车的链接插入到图标 - Woocommerce
- python - 使用自签名证书运行 Flask 时出错“没有这样的文件或目录”
- xcode - Xcode 10.1 打开错误的文件
- r - 如何让我的点在绘图中连接并显示数据中 NA 值的趋势?
- android - 检测应用程序何时从 android O 和 P 中的最近应用程序列表中被杀死