简体   繁体   English

如何在不更改元素顺序的情况下合并两个unordered_maps?

[英]How to merge two unordered_maps without changing the order of the elements?

I need to merge two unordered_map s without changing the order. 我需要合并两个unordered_map而不更改顺序。 For example, 例如,

unordered_map<int,int> map1 ,map2, map3;

map1 contains : <4,4> <2,2> map1包含:<4,4> <2,2>

map2 contains : <3,3> <1,1> map2包含:<3,3> <1,1>

map1 and map2 to be merged with map3. map1和map2与map3合并。

so my map3 should contain <4,4><2,2><3,3><1,1> 所以我的map3应该包含<4,4> <2,2> <3,3> <1,1>

map<int,int>::iterator it   = map3.begin();
std::merge(map1.begin(),map1.end(),map2.begin(),map2.end(),inserter(map3,it));

Still map3 order is changing. 仍然map3的顺序正在变化。 I have tried with std::merge and insert, but nothing worked as per the above req. 我已经尝试过std :: merge和insert,但是按照上面的要求没有任何作用。 Can someone help me on this. 有人可以帮我吗 or am i doing some mistake on merge and insert? 还是我在合并和插入时犯了一些错误?

std::unordered_map doesn't guarantee any kind of order, while std::map is always in sorted order by key (though you can specify your own comparison function). std::unordered_map不保证任何类型的顺序,而std::map始终按键进行排序(尽管您可以指定自己的比较函数)。 It looks like you want items in their order of insertion. 看起来您想要按插入顺序排列的项目。 In this case you can just push your data to a std::vector , although you will have to give up the sublinear operations that the mapped types provide. 在这种情况下,您可以将数据推送到std::vector ,尽管您将不得不放弃映射类型提供的亚线性运算。

There order of map elements dependent of its keys and balanced tree algorithm but not of source map elements order. 地图元素的顺序取决于其键和平衡树算法,而不取决于源地图元素的顺序。 If you want to save order use std::vector<std::pair<inr,int>> instead. 如果要保存订单,请使用std::vector<std::pair<inr,int>>

std::merge works assuming two already sorted ranges (in your case two unsorted maps) achieving linear time performance. std :: merge假设两个已经排序的范围(在您的情况下为两个未排序的映射)实现线性时间性能,则可以正常工作。 Due to its implementation, using unsorted maps will not give the required result. 由于其实现,使用未排序的地图将无法获得所需的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM