Given a vector
of unordered_map
,
I would like to check if the vector
contains any duplicated values. Two unordered_maps a
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> v)
{
std::unordered_map> 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.