c++ - 如何使用 merge 合并两个映射/多映射 (C++11 STL)

标签 c++ stl merge multimap

我的项目处理分而治之策略以并行化现有算法。 该算法返回 std::multimap<int, std::pair<int, int>> .以上是初步(单线程)版本的草图。

typedef std::multimap<int, std::pair<int, int>> Map ;
struct Box
{
  std::pair<int, int> top_left, bottom_right ;
}
Map my_algo(Box, a_box)
{
  Map final_m ;
  if (not is_small(a_box))
  {
    box b1, b2 ;
    split_box(a_box, &b1, &b2) ; // this function divides the box in two halves
    Map m1 = my_algo(b1) ;
    Map m2 = my_algo(b2) ;

    // this line will not compile. final_m.begin() is not accepted.
    std::merge (m1.begin(), m1.end(), m2.begin(), m2.end(), final_m.begin()) ; 
  }
 return final_m ;
}

我知道我可以改用 insert 或 merge 来进行合并(如 here 所述)。但是插入是在 O(N.Log(n)) 中,而合并是在 O((N)) 中。由于算法中涉及合并操作的数量,时间复杂度很重要。

感谢您的帮助, 奥利维尔

编辑:

感谢 jogojapan(见下面的回答),这是更正代码的工作演示:

#include <iostream>
#include <map>
#include <iterator>
#include <algorithm>

typedef std::pair<int, int> Cell ;
typedef std::multimap<int, Cell> Border_map ;

void test_merge_maps_1()
{
Border_map a, b, c ;
std::cout << std::endl << "a" << std::endl ;
for (int i=1; i<10; i+=2)
{
    a.insert(std::pair<int, Cell>(i, Cell(i,i))) ;
    std::cout << i << " " ;
}

std::cout << std::endl << "b" << std::endl ;
for (int i=2; i<11; i+=2)
{
    b.insert(std::pair<int, Cell>(i, Cell(i,i))) ;
    std::cout << i << " " ;
}

std::cout << std::endl << "merge" << std::endl ;
std::merge(a.begin(), a.end(), b.begin(), b.end(), inserter(c,end(c))) ;

std::cout << "result" << std::endl ;
for(auto x: c)
    std::cout << x.first << " " ;
std::cout << std::endl ;
}

int main(void)
{
    test_merge_maps_1() ;
    return 0 ;
}

最佳答案

是的,multimap<T>::begin()返回一个普通(双向)迭代器,但您需要一个能够进行插入的迭代器。您可以使用 std::inserter 获得一个来自 iterator 的模板 header :

#include <iterator>

/* ... */

std::merge(begin(m1),end(m1),begin(m2),end(m2),inserter(final_m,end(final_m)));

如您所见,std::inserter有两个参数:您需要插入迭代器的容器(即 final_m ),以及同一容器的普通迭代器,用作插入的起点。由于合并操作的性质,插入的起始点应该是正在创建的多映射的结束。因此,我使用了 end(final_m) (与 final_m.end() 相同)作为第二个参数。

关于c++ - 如何使用 merge 合并两个映射/多映射 (C++11 STL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13229008/

相关文章:

c++ - 类模板的可视方法何时实例化?

c++ - Windows API的STL成员变量初始化问题

C++ 应该重载函数还是 if 语句就足够了?

c++ - 删除STL Map中匹配值的所有条目

Git merge 不获取新文件

Git:在 rebase 失败后恢复分歧的存储库

c++ - 数据压缩算法

c++ - 如何覆盖类内定义的枚举的 std::hash?

c++ - 自定义类集的重载提取运算符

sql-server - 在存储过程中批处理多个合并是个好主意吗