如何将一张地图的内容附加到另一张地图?
我有以下两个地图:
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
然后我将 map1
的内容复制到 map2
中,如下所示:
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
中的现有内容。 那么,我该怎么做呢?
I have the following two maps:
map< string, list < string > > map1;
map< string, list < string > > map2;
I populated map1
with the following content:
1. kiran; c:\pf\kiran.mdf, c:\pf\kiran.ldf
2. test; c:\pf\test.mdf, c:\pf\test.mdf
Then I copied the content of map1
into map2
as follows:
map2 = map1;
Then I filled map1
again with the following new content:
1. temp; c:\pf\test.mdf, c:\pf\test.ldf
2. model; c:\model\model.mdf, c:\pf\model.ldf
Now I have to append this content to map2
. I cannot use map2 = map1;
, because this will overwrite the existing content in map2
. So, how can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以通过多种方式执行此操作,具体取决于您想要执行的操作:
使用复制构造函数:
按照问题中的指示使用赋值运算符:
手动完成所有操作:
听起来 (1) 就是您想要的。
You can do this several ways depending on what you want to do:
Use the copy constructor:
Use the assignment operator as you indicate in the question:
Do it all yourself manually:
It sounds like (1) is what you want.
自 C++17
std::map
提供了merge()
成员函数。 它允许您从一张地图中提取内容并将其插入到另一张地图中。 基于您的数据的示例代码可以编写如下:输出:
注意:
kiran
、test
、temp
,model
在您的示例中)。 如果两个映射包含相同的键,则相应的元素将不会合并到map2
中,而是保留在map1
中。map2
中,则map1
将变为空。merge()
函数非常高效,因为元素既不被复制也不被移动。 相反,仅重定向映射节点的内部指针。Coliru 上的代码
Since C++17
std::map
provides amerge()
member function. It allows you to extract content from one map and insert it into another map. Example code based on your data could be written as follows:Output:
Notes:
kiran
,test
,temp
,model
in your example). If both maps contain the same key, then the corresponding element will not be merged intomap2
and remain inmap1
.map2
, thenmap1
will become empty.merge()
function is quite efficient, because element are neither copied nor moved. Instead, only the internal pointers of the map nodes are redirected.Code on Coliru
如果您想按照定义插入地图,这很好:
If you want to insert your map as you define it, this is nice:
这会将
map2
从开头到结尾的元素插入到map1
中。 此方法是所有 STL 数据结构的标准方法,因此您甚至可以执行类似的操作此外,指针还可以用作迭代器!
强烈建议学习 STL 和迭代器的魔力!
This will insert into
map1
the elements from the beginning to the end ofmap2
. This method is standard to all STL data structure, so you could even do something likeFurthermore, pointers can also function as iterators!
Highly recommend studying the magic of the STL and iterators!
您可以使用地图的插入方法。 例如:
You can use use insert method of the map. For example: