Given a vector
of unordered_map
,
I would like to check if the vector
contains any duplicated values. Two unordered_maps a
you can something similar to the following :
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();
If you can get a good hash function for std::unordered_map then you should do it like this probably:
bool has_distinct_values(const std::vector<std::unordered_map<u_int, int>> v)
{
std::unordered_map<int, std::list<int>> hash_to_indexes_map;
for(auto i = 0u; i < v.size(); ++i)
{
auto empl_result = hash_to_index_map.emplace(custom_hash(v[i]), {i});
if (!empl_result.second)
{
for (auto index : empl_result.first->second)
{
if (v[index] == v[i]) return false;
}
epmpl_result.first->second.push_back(i);
}
}
return true;
}
The algorithm is straightforward: map hashes to list indexes, doing pairwise map comparison whenever hashes are equal. This way you avoid copying the entire maps, get O(N) (depending mostly on the quality of the hash function you provide) time complexity and generally are good to go.