multiset, map and hash map complexity

你。 提交于 2019-11-26 08:45:40

问题


I would like to know the complexity in Big O notation of the STL multiset, map and hash map classes when:

  • inserting entries
  • accessing entries
  • retrieving entries
  • comparing entries

回答1:


map, set, multimap, and multiset

These are implemented using a red-black tree, a type of balanced binary search tree. They have the following asymptotic run times:

Insertion: O(log n)
Lookup: O(log n)
Deletion: O(log n)

hash_map, hash_set, hash_multimap, and hash_multiset

These are implemented using hash tables. They have the following runtimes:

Insertion: O(1) expected, O(n) worst case
Lookup: O(1) expected, O(n) worst case
Deletion: O(1) expected, O(n) worst case

If you use a proper hash function, you'll almost never see the worst case behavior, but it is something to keep in mind — see Denial of Service via Algorithmic Complexity Attacks by Crosby and Wallach for an example of that.




回答2:


You can find this information in the SGI STL documentation: http://www.sgi.com/tech/stl/

Basically, both multiset and maps are sorted binary trees, so inserting/finding 1 out of N entries takes O(log N). See Sorted Assoc. Containers in the documentation.

Obviously, the big advantage of Hashmap is O(1) for inserting and finding entries.

Accessing it after found is O(1) for all structures. Comparison, what do you mean by that? Sounds like O(1) to me, after all were found.



来源:https://stackoverflow.com/questions/222658/multiset-map-and-hash-map-complexity

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