如何将一张地图的内容附加到另一张地图?

Cut*_*ute 19 c++ stl visual-c++

我有两张地图:

map< string, list < string > > map1;
map< string, list < string > > map2;
Run Code Online (Sandbox Code Playgroud)

我已经填充了map1,现在我想将map1内容复制到map2中.所以我只是做了:

我有一些map1填充的操作

 1. kiran, c:\pf\kiran.mdf, c:\pf\kiran.ldf
 2. test,  c:\pf\test.mdf, c:\pf\test.mdf
Run Code Online (Sandbox Code Playgroud)

现在我必须用这个内容填充map2.并且map1填充了信息

 1. temp, c:\pf\test.mdf, c:\pf\test.ldf
 2. model, c:\model\model.mdf, c:\pf\model.ldf
Run Code Online (Sandbox Code Playgroud)

现在我必须将这些内容附加到map2.我该怎么做呢?

Nic*_*wis 51

map<int,int> map1;
map<int,int> map2;
map1.insert(map2.begin(), map2.end());
Run Code Online (Sandbox Code Playgroud)

这将从map1开头到结尾插入元素map2.这种方法是所有STL数据结构的标准,所以你甚至可以做类似的事情

map<int,int> map1;
vector<pair<int,int>> vector1;
vector1.insert(map1.begin(), map1.end());
Run Code Online (Sandbox Code Playgroud)

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

char str1[] = "Hello world";
string str2;
str2.insert(str1, str1+strlen(str1));
Run Code Online (Sandbox Code Playgroud)

强烈建议研究STL和迭代器的神奇之处!

  • 在C++中,>>之间的空间不是必需的. (2认同)
  • 如果不需要 map2,请使用 `std::make_move_iterator`。 (2认同)

Nav*_*een 7

您可以使用map的insert方法.例如:

   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());
Run Code Online (Sandbox Code Playgroud)


Gre*_*reg 4

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

  1. 使用复制构造函数:

    map< string, list < string > > map1;
    // fill in map1
    
    map< string, list < string > > map2(map1);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 按照问题中的指示使用赋值运算符:

    map< string, list < string > > map1;
    map< string, list < string > > map2;
    
    // fill in map1
    
    map2 = map1;
    
    Run Code Online (Sandbox Code Playgroud)
  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();
    }
    
    Run Code Online (Sandbox Code Playgroud)

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