25

我有以下两张地图:

map< string, list < string > > map1;
map< string, list < string > > map2;

我填充map1了以下内容:

1. kiran; c:\pf\kiran.mdf, c:\pf\kiran.ldf
2. test;  c:\pf\test.mdf, c:\pf\test.mdf

然后我将内容复制map1map2如下:

map2 = map1;

然后我再次填充map1了以下新内容:

1. temp; c:\pf\test.mdf, c:\pf\test.ldf
2. model; c:\model\model.mdf, c:\pf\model.ldf

现在我必须将此内容附加到map2. 我不能使用map2 = map1;,因为这会覆盖map2. 那么,我该怎么做呢?

4

5 回答 5

60
map<int,int> map1;
map<int,int> map2;
map1.insert(map2.begin(), map2.end());

这将插入map1从开头到结尾的元素map2。此方法是所有 STL 数据结构的标准方法,因此您甚至可以执行类似的操作

map<int,int> map1;
vector<pair<int,int>> vector1;
vector1.insert(map1.begin(), map1.end());

此外,指针也可以用作迭代器!

char str1[] = "Hello world";
string str2;
str2.insert(str1, str1+strlen(str1));

强烈推荐学习 STL 和迭代器的魔力!

于 2009-07-14T20:43:50.133 回答
7

您可以使用地图的插入方法。例如:

   std::map<int, int> map1;
    std::map<int, int> map2;

    map1[1] = 1;

    map2.insert(map1.begin(), map1.end());
    map1.clear();

    map1[2] =2;
    map2.insert(map1.begin(), map1.end());
于 2009-07-01T06:23:39.380 回答
3

您可以通过多种方式执行此操作,具体取决于您要执行的操作:

  1. 使用复制构造函数:

    map< string, list < string > > map1;
    // fill in map1
    
    map< string, list < string > > map2(map1);
    
  2. 如您在问题中指出的那样使用赋值运算符:

    map< string, list < string > > map1;
    map< string, list < string > > map2;
    
    // fill in map1
    
    map2 = map1;
    
  3. 自己手动完成:

    map< string, list < string > > map1;
    map< string, list < string > > map2;
    
    // fill in map1
    
    for (map< string, list < string > >::iterator i = map1.begin();
         i <= map1.end(); ++i) {
      map2[i.first()] = i.second();
    }
    

听起来(1)是你想要的。

于 2009-07-01T06:04:15.980 回答
0

如果您想在定义时插入地图,这很好:

payload.insert({
            { "key1", "one" },
            { "key2", 2 },
        });
于 2016-03-17T01:34:34.143 回答
0

由于C++17 std::map提供了一个merge()成员函数。它允许您从一张地图中提取内容并将其插入到另一张地图中。基于您的数据的示例代码可以编写如下:

using myMap = std::map<std::string, std::list<std::string>>;

myMap  map2 = { {"kiran", {"c:\\pf\\kiran.mdf", "c:\\pf\\kiran.ldf"}},
                {"test",  {"c:\\pf\\test.mdf",  "c:\\pf\\test.mdf"}} };

myMap  map1 = { {"temp",  {"c:\\pf\\test.mdff",    "c:\\pf\\test.ldf"}},
                {"model", {"c:\\model\\model.mdf", "c:\\pf\\model.ldf"}} };

map2.merge(map1);

for (auto const &kv : map2) {
    std::cout << kv.first << " ->";
    for (auto const &str : kv.second)
        std::cout << " " << str;
    std::cout << std::endl;
}

输出:

kiran -> c:\pf\kiran.mdf c:\pf\kiran.ldf
模型 -> c:\model\model.mdf c:\pf\model.ldf
temp -> c:\pf\test.mdff c :\pf\test.ldf
测试 -> c:\pf\test.mdf c:\pf\test.mdf

笔记:

  • 一个键只能在地图中存在一次(即,kiran在您的示例中)。如果两个 map 包含相同的 key,则相应的元素将不会合并到并保留在.testtempmodelmap2map1
  • 如果所有元素都可以合并到map2中,map1则将变为空。
  • merge()功能非常有效,因为元素既不复制也不移动。相反,只有映射节点的内部指针被重定向。

Coliru 上的代码

于 2020-03-13T12:02:55.560 回答