Given that I have two std::map
s, say:
map<int, double> A;
map<int, double> B;
I'd like to get the intersection of the two maps, something of the form:
map<int, pair<double,double> > C;
Where the keys are the values in both A
and B
and the value is a pair of the values from A
and B
respectively.
Is there a clean way using the standard-library?
I haven't tested this, or even compiled it... but it should be O(n). Because it's templated it should work with any two maps that share the same key type.
The following is a simplification of my previous answer, mostly taking advantage of the fact that set_intersection CAN be used with maps as input, but only if you make the output a set of std::pairs. The result also cuts down intermediates to a single "common keys" list.
EDIT: Since I was pretty sure there was a better STL-like solution to this, I figured one out. It's different enough that I'm posting it as a separate answer.
There are a few tricks to this. Firstly, you'd like to use set_intersection, but you have two maps. The solution is a custom comparator and the std::transform algorithm. Someone more familiar with the standard library than me can probably optimize this, but it works. Note that boost::bind would allow you to cut down on the silly helper functions that make this work.
Like much of C++, the final use of everything is fairly slick (everything in main()), but the setup is more verbose than we would really like.
Okay, let's get ready to get your hands dirty :)
I'll be using
std::mismatch
andstd::transform
First of all, some types:
Then predicates
Now main:
I find this solution quite elegant... notwithstanding the awkard setup part since we need to ensure that the first range ends up quicker than the second because of
mismatch
...Notice that the advance is really stupid, we could loop specifically here until we had
*next.first.key == *next.second.key
but it would complicate the loop.I really don't find this better than a handcrafted loop though... consider:
It's much more compact, probably more efficient... sometimes the functions you're looking are not general enough to be in the STL :)
Almost a year after... but nevertheless :)
This one is for a set container, but you can easily change it to use a map:
Usage:
set1 and set2 are both set containers whilst output_container can be set, list, array etc..
inserter generates an insert iterator