插入新密钥时,保持unordered_map的顺序 [英] Keep the order of unordered_map as we insert a new key
问题描述
我使用以下代码将元素插入 unordered_map
:
myMap.insert(std :: make_pair( A,10));
myMap.insert(std :: make_pair( B,11));
myMap.insert(std :: make_pair( C,12));
myMap.insert(std :: make_pair( D,13));
但是当我使用此命令打印键时
用于(const auto i:myMap)
{
cout<< i。第一<< std :: endl;
}
它们的插入顺序与我插入的顺序不同。
是否可以保留订单?
不,不可能。
使用 std :: unordered_map
不能为您提供任何元素顺序保证。
如果要按地图关键字对元素进行排序(如您的示例所示),则应使用 std :: map
。 / p>
如果您需要保留有序对的列表,可以使用 std :: vector< std :: pair< std :: string,int>> ;
。
I inserted the elements to the unordered_map
with this code:
myMap.insert(std::make_pair("A", 10));
myMap.insert(std::make_pair("B", 11));
myMap.insert(std::make_pair("C", 12));
myMap.insert(std::make_pair("D", 13));
But when I used this command to print the keys
for (const auto i : myMap)
{
cout << i.first << std::endl;
}
they are not in the same order as I inserted them.
Is it possible to keep the order?
No, it is not possible.
Usage of std::unordered_map
doesn't give you any guarantee on element order.
If you want to keep elements sorted by map keys (as seems from your example) you should use std::map
.
If you need to keep list of ordered pairs you can use std::vector<std::pair<std::string,int>>
.
这篇关于插入新密钥时,保持unordered_map的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!