假设Amap2 为空,您在上面发布的代码将正常工作。如果您尝试将一个键/值对insert 转换为已经拥有该键的map,那么旧值将被保留而新值将被丢弃。因此,如果你写
Amap2.insert(Amap1.begin(), Amap1.end());
在某些情况下,您可能无法按预期复制所有内容,因为不会复制重复的键。
要将Amap2 设置为等于Amap1,请考虑仅使用赋值运算符:
Amap2 = Amap1;
不过,这会盲目地丢弃Amap2 的内容,所以这样做时要小心。
如果您想要以完全覆盖现有键/值对的方式将 Amap2 中的所有键/值对添加到 Amap1 中,则可以使用以下逻辑执行此操作。这里的想法类似于合并排序背后的逻辑——我们将映射视为排序值的序列,然后不断地将两者混合在一起:
void MergeMaps(map<int, A>& lhs, const map<int, A>& rhs) {
map<int, A>::iterator lhsItr = lhs.begin();
map<int, A>::const_iterator rhsItr = rhs.begin();
while (lhsItr != lhs.end() && rhsItr != rhs.end()) {
/* If the rhs value is less than the lhs value, then insert it into the
lhs map and skip past it. */
if (rhsItr->first < lhsItr->first) {
lhs.insert(lhsItr, *rhsItr); // Use lhsItr as a hint.
++rhsItr;
}
/* Otherwise, if the values are equal, overwrite the lhs value and move both
iterators forward. */
else if (rhsItr->first == lhsItr->first) {
lhsItr->second = rhsItr->second;
++lhsItr; ++rhsItr;
}
/* Otherwise the rhs value is bigger, so skip past the lhs value. */
else
++lhsItr;
}
/* At this point we've exhausted one of the two ranges. Add what's left of the
rhs values to the lhs map, since we know there are no duplicates there. */
lhs.insert(rhsItr, rhs.end());
}
有了这个,你可以写
MergeMaps(Amap1, Amap2);
将所有键/值对从Amap2 复制到Amap1。
希望这会有所帮助!