繁体   English   中英

将std :: map数据复制到另一个地图

[英]Copy std::map data to another map

我有一个像这样定义的地图

 struct A
 {
  int A;
  int B;
 };
 typedef map<int,A> Amap;

然后我有Amap1 ,我想把它复制到Amap2

 A a....;
 Amap Amap1,Amap2;
 Amap1[1]=a1;
 Amap1[2]=a2;
 Amap1[3]=a3;
 Amap2.insert(Amap1.begin(), Amap1.end());

有时这工作正常,有时这只复制键和值0.这里我的错误在哪里?

可以使用operator =或复制构造函数将一个映射复制到另一个映射。

例如

map<X, Y> mp1; 
//fill mp1 with data
map<X, Y> mp2(mp1); //mp2 is a copy of mp1 (via copy-construction)
map<X, Y> mp3;
mp3 = mp2; // mp3 is also a copy of mp2 (via copy-assignment)

假设Amap2为空,您上面发布的代码将正常工作。 如果您尝试insert键/值对插入已保存该键的map中,则将保留旧值并丢弃新值。 因此,如果你写

Amap2.insert(Amap1.begin(), Amap1.end());

在某些情况下,您可能无法按预期复制所有内容,因为重复的密钥不会复制。

要将Amap2设置Amap2等于Amap1 ,请考虑使用赋值运算符:

Amap2 = Amap1;

但是,这会盲目地丢弃Amap2的内容,所以在这样做时要小心。

如果您想要做的是将Amap1中的所有键/值对以完全覆盖现有键/值对的方式Amap2Amap1中,您可以使用以下逻辑执行此操作。 这里的想法类似于mergesort背后的逻辑 - 我们将地图视为排序值的序列,然后将两者连续混合在一起:

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);

将所有键/值对从Amap2Amap1

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM