order of elements in std::unordered_multimap

ぃ、小莉子 提交于 2019-12-23 17:30:22

问题


If I have the following piece of code

std::unordered_multimap<std::string, std::vector<double>> myMap;
std::vector<double> v1, v2, v3;
// init v1, v2, v3....
myMap.insert(std::make_pair<std::string, std::vector<double>("vec", v1));
myMap.insert(std::make_pair<std::string, std::vector<double>("vec", v2));
myMap.insert(std::make_pair<std::string, std::vector<double>("vec", v3));

If I access the values with an iterator they will always be in this order: v1, v2, v3

So basically if I insert elements of the same key, but different value, do they always retain the order of insertion?


回答1:


I guess this is implementation specific. In an unordered_multimap elements with same key are stored in the same bucket if the implementation is a bucket hash map, in this case they could be in the same order of insertion (that is probably your situation).

But in an unordered_map implemented, for example, with an open addressing technique, the order could change. I don't know if there are STL implementations which uses different under the hood implementation but the contract of the class doesn't make any assumption on the order of the values for the same key so I don't think you can take it for granted.

Taken from here:

Internally, the elements in the unordered_map are not sorted in any particular order with respect to either their key or mapped values




回答2:


The whole point of "unordered" in the name is that you can't rely on the order. Ever.

If you detect any order coming from iterating the container, it's a coincidence or an artifact of the implementation. You should never count on it.




回答3:


Unless the documentation says that they'll always be returned in insertion order, you would be doing the wrong thing to rely on it. The STL implementation you use today could change. It also might be the case that the implementation you're using would work differently if there were a lot of entries in the map.



来源:https://stackoverflow.com/questions/14346361/order-of-elements-in-stdunordered-multimap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!