multiset, map and hash map complexity

前端 未结 2 1539
一生所求
一生所求 2020-11-28 18:41

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
相关标签:
2条回答
  • 2020-11-28 19:25

    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.

    0 讨论(0)
  • 2020-11-28 19:35

    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.

    0 讨论(0)
提交回复
热议问题