Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersection of two `std::map`s

Given that I have two std::maps, 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?

like image 921
Hooked Avatar asked Sep 22 '10 18:09

Hooked


People also ask

Can we equate two maps in C++?

The C++ function std::map::operator== tests whether two maps are equal or not.

Does std::map use == operator?

They won't use operator==() . The only comparison used to locate objects is the third template argument to std::map<K, V, Compare, Allocator> .

Are std :: maps ordered?

Yes, a std::map<K,V> is ordered based on the key, K , using std::less<K> to compare objects, by default.

Does std::map allow duplicates?

Duplicate keys are not allowed in a map : map insert « map multimap « C++ Tutorial. 23.6. 1. Insert characters into map.


1 Answers

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.

like image 199
Mark Ransom Avatar answered Sep 19 '22 21:09

Mark Ransom