c++ - Intersection of two STL maps -
given have 2 stl maps, say:
map<int, double> a; map<int, double> b;
i'd intersection of 2 maps, of form:
map<int, pair<double,double> > c;
where keys values in both , b , value pair of values , b respectively. there clean stl-like way go this?
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 compiled it... should o(n). because it's templated should work 2 maps share same key type.
Comments
Post a Comment