c++ - 算法:合并 std::unordered_map

标签 c++ algorithm boost

我有以下问题:

我有 n 个从 std::string 映射到 boost::variant 的 HashMap (我们称它们为 A.1、A.2、...、A.n),我想将它们合并到一个 HashMap (我们称B) 如下:

  1. 如果 A.1、A.2、...A.n 包含相同的 key K 值,则 B 应该包含相同的 key K 值。
  2. 如果存在某个键 K 不存在于映射 A.1、A.2、... A.n 之一中,则 B 应包含从键 K 到值 boost::blank 的映射。
  3. 如果 A.1、A.2、...A.n 中的键 K 存在与其他值不同的某个值,则 B 应包含从键 K 到值 boost::blank 的映射。

我必须经常这样做,而且我知道这会成为瓶颈。实现这一目标最有效的方法是什么?有库支持像这样合并 HashMap 吗?

编辑:如果其他数据结构更合适,请告诉我。然而,我确实需要 O(1) 查找

最佳答案

如果我没看错的话,您正在寻找一个O(N log N) 解决方案。如果没有 C++ 经验来编写正确的实现,您想要做的就是以下几行:

1) Push all of the elements from every map into a `Set`   `O(N) + overhead of checking existence O(1)`  
   A)  define the elements of the set by a hash value generated by `Key + Value`   
      a)  that is `A:hello`  creates a different value than `B:hello`  
2) Perform a merge sort `O(N log N)` based on the values  
3) Start at the beginning of your `sorted set` and iterate over the values.  
   A) If a value is found multiple times this satisfies your `3` step  
   B) Your `2` step can be satisifed in `O(1)` time by looking up the key

关于c++ - 算法:合并 std::unordered_map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15704787/

相关文章:

c++ - C++中的智能数据结构可保存数据以加快访问速度

c++ - 段错误将引用作为函数参数传递

algorithm - 如何用 3 个变量解决背包问题?

c++ - 解析 json 后 boost 属性树无法检索记录

c++ - 如何在 Visual C++ Express 2010 中编译此逻辑

c++ - 使用 GENICAM API 和 C++ 使用 OpenCV 创建适用于各种相机的程序

python - 如何在不使用希尔伯特索引的情况下沿希尔伯特曲线对点进行排序?

c++ - Bubblesort 让我抓狂

c++ - Boost.Fusion 定义结构数组成员

c++ - 定义 BOOST_TEST_DYN_LINK 会导致应用程序在 Visual Studio 中崩溃