合并两个STL映射 [英] Merge two STL maps

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

问题描述

如何将两个STL地图合并成一个?它们都具有相同的键值类型(映射)。如果有键的重叠,我想优先选择一个地图。

解决方案

假设您想保留mapA中的元素,并在mapB中合并元素,而mapA中没有键: / p>

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



编辑:添加工作示例

  #include< iostream> 
#include< map>

void printIt(std :: map for(std :: map< int,int> :: iterator it = m.begin() != m.end(); ++ it)
std :: cout< it->第一<<:<< it->第二<<
std :: cout<< \\\
;
}

int main(){
std :: map< int,int> ;
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


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

解决方案

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.

EDIT: adding working example

#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;
}

output:

:!./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天全站免登陆