c++ - unordered_map complexity

后端 未结 3 2002
不知归路
不知归路 2020-12-11 01:19

I need to create a lookup function where a (X,Y) pair corresponds to a specific Z value. One major requirement for this is that I need to do it in as close to O(1) complexi

3条回答
  •  佛祖请我去吃肉
    2020-12-11 01:48

    As with any hash table, worst case is always linear complexity (Edit: if you built the map without any collisions like you stated in your original post, then you'll never see this case):

    http://www.cplusplus.com/reference/unordered_map/unordered_map/find/

    Complexity Average case: constant. Worst case: linear in container size.

    Return Value An iterator to the element, if the specified key value is found, or unordered_map::end if the specified key is not found in the container.

    However, because an unordered_map can only contain unique keys, you will see average complexity of constant time (container first checks hash index, and then iterates over values at that index).

    I think the documentation for unordered_map::count function is more informative:

    Searches the container for elements whose key is k and returns the number of elements found. Because unordered_map containers do not allow for duplicate keys, this means that the function actually returns 1 if an element with that key exists in the container, and zero otherwise.

提交回复
热议问题