Reputation: 343
I just wonder if there is any sexy way in C++ (using standard library functions) to do something like that:
I've got two maps (std::map), both same type. I'd like to add both maps together, but also decide which elements add and which not with some lambda predicate.
Any solution? Thanks.
Upvotes: 3
Views: 250
Reputation: 65600
You can use std::copy_if
in combination with std::inserter
. This example only adds elements from b
into a
if the value is even:
std::copy_if(b.begin(), b.end(), std::inserter(a, a.end()),
[](auto&& e){return e.second%2 == 0;});
You could factor this out into a helper function if you find yourself needing this a few times:
template <typename T, typename F>
void merge_maps (T& a, const T& b, const F& filter) {
std::copy_if(b.begin(), b.end(), std::inserter(a, a.end()), filter);
}
merge_maps(a, b, [](auto&& e){return e.second%2 == 0;});
Upvotes: 6