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?
The C++ function std::map::operator== tests whether two maps are equal or not.
They won't use operator==() . The only comparison used to locate objects is the third template argument to std::map<K, V, Compare, Allocator> .
Yes, a std::map<K,V> is ordered based on the key, K , using std::less<K> to compare objects, by default.
Duplicate keys are not allowed in a map : map insert « map multimap « C++ Tutorial. 23.6. 1. Insert characters into map.
template<typename KeyType, typename LeftValue, typename RightValue>
map<KeyType, pair<LeftValue, RightValue> > IntersectMaps(const map<KeyType, LeftValue> & left, const map<KeyType, RightValue> & right)
{
map<KeyType, pair<LeftValue, RightValue> > result;
typename map<KeyType, LeftValue>::const_iterator il = left.begin();
typename map<KeyType, RightValue>::const_iterator ir = right.begin();
while (il != left.end() && ir != right.end())
{
if (il->first < ir->first)
++il;
else if (ir->first < il->first)
++ir;
else
{
result.insert(make_pair(il->first, make_pair(il->second, ir->second)));
++il;
++ir;
}
}
return result;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With