首先想到的是std::merge算法。不幸的是,源和目标范围的值类型不兼容,所以我们需要一些可以为我们转换它的东西。 Boost 通过Function Output Iterator 提供了一个很好的工具。分配给此输出迭代器的任何内容都作为参数传递给它包装的一元函数。与 lambdas 一起,这非常简单:
#include <boost/function_output_iterator.hpp>
std::map<char, int> m1 { {'a',1}, {'b',2}, {'c',3} };
std::map<char, int> m2 { {'a',5}, {'c',6}, {'e',7} };
std::map<char, std::vector<int>> m3;
typedef std::map<char, int>::value_type source_type;
auto push_value =
[&m3](const source_type& p) { m3[p.first].push_back(p.second); };
std::merge(m1.begin(), m1.end(), m2.begin(), m2.end(),
boost::make_function_output_iterator(push_value));
这还不是我们想要的。 m3 看起来像这样:
a - 1 5
b - 2
c - 3 6
e - 7
对于在m2 但不在m1 中的键,我们需要在向量的前面挤压一个零。我们可以在合并之前使用set_difference 来做到这一点。我们需要使用只比较地图键的自定义比较器:
auto push_zero =
[&m3](const source_type& p) { m3[p.first].push_back(0); };
auto cmp =
[](const source_type& p1, const source_type& p2) { return p1.first < p2.first; };
std::set_difference(m2.begin(), m2.end(), m1.begin(), m1.end(),
boost::make_function_output_iterator(push_zero), cmp);
m3 现在是:
a - 1 5
b - 2
c - 3 6
e - 0 7
在第三步中,我们为m1 中但不在m2 中的键添加一个零:
std::set_difference(m1.begin(), m1.end(), m2.begin(), m2.end(),
boost::make_function_output_iterator(push_zero), cmp);
现在我们得到了我们想要的:
a - 1 5
b - 2 0
c - 3 6
e - 0 7
请参阅LiveWorkspace 上的完整示例。