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

时间:2011-06-22 08:37:18

标签: c++

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

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

5 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:1)

Mat指出,这取决于您是否需要按排序顺序访问元素。此外,map具有保证最坏情况对数访问时间(元素数量),而无序映射具有平均常量访问时间。

答案 2 :(得分:1)

使用map代替unordered_map的主要原因是map是标准的,并且您肯定拥有它。有些公司的政策是不使用tr1中的定义 但是,当您下订单很重要时,您会询问它是否需要lower_boundupper_boundset_unionset_intersection等操作。

答案 3 :(得分:1)

如果需要无序容器之间的比较,那么复杂性 可能是一个问题 似乎很难在两者之间实施operator== / operator!= 有效的无序容器。
N3290§23.2.5/ 11说

  

operator == ...的复杂性   与...... N ^ 2成正比   case,其中N是a.size()。

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

答案 4 :(得分:-1)

Unordered_map使用的内存多于map。如果内存中存在约束,则建议使用map。因此,使用unordered_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.