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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…