如何合并两个STL映射? [英] How can I merge two STL maps?

查看:111
本文介绍了如何合并两个STL映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将两个STL映射合并为一个?它们都具有相同的键和值类型(map<string, string>).如果按键重叠,我想优先选择其中一张地图.

How can I merge two STL maps into one? They both have the same key and value types (map<string, string>). If there is an overlap of the keys, I would like to give preference to one of the maps.

推荐答案

假定要保留mapA中的元素,并合并mapB中没有键的元素mapA:

Assuming you want to preserve the elements in mapA, and merge elements in mapB for which there is no key in mapA:

mapA.insert(mapB.begin(), mapB.end())

我想

会做你想要的.

will do what you want, I think.

工作示例:

#include <iostream>
#include <map>

void printIt(std::map<int,int> m) {
    for(std::map<int,int>::iterator it=m.begin();it!=m.end();++it)
        std::cout << it->first<<":"<<it->second<<" ";
    std::cout << "\n";
}

int main() {
    std::map<int,int> foo,bar;
    foo[1] = 11; foo[2] = 12; foo[3] = 13;
    bar[2] = 20; bar[3] = 30; bar[4] = 40;
    printIt(foo);
    printIt(bar);
    foo.insert(bar.begin(),bar.end());
    printIt(foo);
    return 0;
}

输出:

:!./insert
1:11 2:12 3:13
2:20 3:30 4:40
1:11 2:12 3:13 4:40

这篇关于如何合并两个STL映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆