How to detect duplicates in a vector of unordered_map?

后端 未结 2 929
死守一世寂寞
死守一世寂寞 2021-02-11 09:36

Given a vector of unordered_map, I would like to check if the vector contains any duplicated values. Two unordered_maps a

2条回答
  •  执笔经年
    2021-02-11 10:33

    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.

提交回复
热议问题