3

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.

3
  • 1
    Do you want to create a third map or mutate one of the two input maps? Commented May 20, 2016 at 9:54
  • 1
    Random thoughts: std::merge, std::set_union, std::multimap, and also consider whether a.key_comp() == b.key_comp() (comparators may be stateful!). Commented May 20, 2016 at 9:57
  • I don't want to use 3rd map, because all elements inside of first map stays, predicate would only determine addition of 2nd map's elements. Commented May 20, 2016 at 9:58

1 Answer 1

6

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;});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.