I have read the Merge two STL maps question, and though it's close, I was looking for functionality like the one described here.
In short, I would like to merge two std::map
instances (having the same key and value type) into one, with the caveat that I would like to add the values together if the object exists in both maps.
Is there an existing boost, range-v3, or std function that can do this? And if not, what would be the best way to achieve it?
Example code:
double mergePredicate(double lhs, double rhs)
{
return lhs + rhs;
}
int main()
{
std::map<int, double> mapA = { {0, 1.0}, {1, 2.0} };
std::map<int, double> mapB = { {1, 1.5}, {2, 2.5} };
// Merge maps in some way...
merge(mapA, mapB, mergePredicate);
// result: mapA == { {0, 1.0}, {1, 3.5}, {2, 2.5} }
for (const auto& p : mapA) {
std::cout << p.first << " " << p.second << std::endl;
}
}