Map3 foo( Map1 const & m1, Map2 const & m2 ) { auto m2end = m2.end(); // a constant call is move outside the loop Map3 result; for( auto & v1 : m1 ) { // each entry in m1 is made of the key as first and the value as second for( auto & p1 : v1.second ) { // iterate over the vector of pair // auto v2it = m2.find( p1 ); // search for the pair auto v2it = m2.find(std::make_pair(p1.first, p1.second)); //search for the pair, where piar element order not important auto v2it2 = m2.find(std::make_pair(p1.second, p1.first)); if ( v2it != m2end ) { result[v1.first] += v2it->second; // if the pair was found, add the value for it to the result, using the map1 key as key } if ( v2it2 != m2end ) { result[v1.first] += v2it2->second; // if the pair was found, add the value for it to the result, using the map1 key as key } } } return result; }