std::map v1 = { {1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}}; std::map<int, int> v2 = { {3, 2}, {4, 2}, {5, 2}, {6, 2}, {7, 2}}; std::map<int, int> dest1 = v1; dest1.insert(v2.begin(), v2.end()); for (const auto &i : dest1) { std::cout << i.first << ':' << i.second << ' '; std::cout << '\n'; 1:1 2:1 3:1 4:1 5:1 6:2 7:2

合并多个map,循环进行即可。

#include <map>
#include <iostream>
int main()
    std::map<int, int> v1 = { {1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1} };
    std::map<int, int> v2 = {  {4, 2}, {5, 2}, {6, 2}, {7, 2} };
    std::map<int, int> v3 = { {8, 2}, {9, 2}};
    std::map<uint32_t, std::map<int, int>> pp;
    pp.insert({ 1,v1 });
    pp.insert({ 2,v2 });
    pp.insert({ 3,v3 });
    std::map<int, int> dest1 ;
    auto iter = pp.begin();
    for (; iter != pp.end(); ++iter) {
        dest1.insert(iter->second.begin(), iter->second.end());
    for (const auto &i : dest1) {
        std::cout << i.first << ':' << i.second << ' ';
    std::cout << '\n';
1:1 2:1 3:1 4:1 5:1 6:2 7:2 8:2 9:2

如果map中有重复的key,并且想保留多个相同key的键值对,则只需要,将目标map定义为 std::multimap 。如下:

#include <map>
#include <iostream>
int main()
    std::map<int, int> v1 = {{1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}};
    std::map<int, int> v2 = {                {3, 2}, {4, 2}, {5, 2}, {6, 2}, {7, 2}};
    std::multimap<int, int> dest1 {v1.begin(), v1.end()};
    dest1.insert(v2.begin(), v2.end());
    for (const auto &i : dest1) {
        std::cout << i.first << ':' << i.second << ' ';
    std::cout << '\n';
1:1 2:1 3:1 3:2 4:1 4:2 5:1 5:2 6:2 7:2

其他容器类似。

// Aa.cpp : Defines the entry point for the console application. #include stdafx.h #include #include #include using namespace std; int main(int argc, char* argv[]) printf(Hello World!\n); vector a; //创建一个对象 a.push_back(1); a.push_back(2); a.push_back(3); 两个map进行合并有多种方式实现,以下列举出几种常见的合并方式: 方式1:使用map的merge()方法进行合并 public class MergeTwoMaps { public static void main(String[] args) { Map<Integer,Integer> map1 = new HashMap<>(); map1.put(1,1); map1.put(2,2); 本文实例讲述了ES6中Set和Map数据结构,Map与其它数据结构互相转换操作。分享给大家供大家参考,具体如下: ES6 的 Set: ES6 提供了新的数据结构──Set。它类似于数组,但是员的值都是唯一的,没有重复的值。 Set 本身是一个构造函数,用来生 Set 数据结构。 Array和Set对比 都是一个存储多值的容器,两者可以互相转换,但是在使用场景上有区别。如下: ①Array的indexOf方法比Set的has方法效率低下 ②Set不含有重复值(可以利用这个特性实现对一个数组的去重) ③Set通过delete方法删除某个值,而Array只能通过splice。两者的使用方便程度 std::map 是有序键值对容器,它的元素的键是唯一的。用比较函数 Compare 排序键。搜索、移除和插入操作拥有对数复杂度。 map 通常实现为红黑树。 在每个标准库使用比较 (Compare) 概念的位置,以等价关系检验唯一性。不精确而言,若二个对象 a 与 b 互相比较不小于对方 : !comp(a, b) && !comp(b, a) ,则认为它们等价(非唯一)。 1.先来一个demopublic static void main(String[] args) { Map&lt;String, String&gt; map1 = new HashMap&lt;String, String&gt;(){{ put("1", "a"); put("2", "b"); put("3", &