键值关联容器中的顺序是有用的用例是什么

what is the uses cases in which order in key value associative container is useful

本文关键字:有用 是什么 顺序 键值 关联      更新时间:2023-10-16

我想知道在哪些用例中,我们可以通过拥有有序的关联容器来感兴趣。

换句话说,为什么使用std::map而不使用std::unorderd_map

当您需要能够以有序的方式迭代键时,可以使用有序映射。

正如Mat所指出的,这取决于您是否需要按排序顺序访问元素。此外,映射具有保证的最坏情况对数访问时间(以元素数量为单位),而无序映射具有平均恒定访问时间。

使用map而不是unordered_map的主要原因是map是标准的,您一定有。一些公司有政策不使用tr1中的定义
但您会问订单什么时候很重要——lower_boundupper_boundset_unionset_intersection等操作都需要订单。

如果需要在无序容器之间进行比较可能是个问题
operator==/operator!=在无序容器
N3290§23.2.5/11称

运算符的复杂性==。。。是与…成比例。。。N^2在最坏的情况下case,其中N是a.size().

而其他容器具有线性复杂性。

Unordered_map比map使用更多内存。如果内存中存在约束,则建议使用贴图。因此,当使用无序映射时,操作会变慢

编辑

引用维基文章

It is similar to the map class in the C++ standard library but has different 
constraints. As its name implies, unlike the map class, the elements of an 
unordered_map are not ordered. This is due to the use of hashing to store objects.
unordered_map can still be iterated through like a regular map.