Time complexity of find() in std::map?

前端 未结 3 1552
迷失自我
迷失自我 2020-12-14 08:19

How efficient is the find() function on the std::map class? Does it iterate through all the elements looking for the key such that it\'s O(n), or is it in a balanced tree, o

3条回答
  •  半阙折子戏
    2020-12-14 08:47

    std::map and std::set are implemented by compiler vendors using highly balanced binary search trees (e.g. red-black tree, AVL tree).

    As correctly pointed out by David, find would take O(log n) time, where n is the number of elements in the container.

    But that's with primitive data types like int, long, char, double etc., not with strings.

    If std:string, lets say of size 'm', is used as key, traversing the height of the balanced binary search tree will require log n comparisons of the given key with an entry of the tree.

    When std::string is the key of the std::map or std::set, find and insert operations will cost O(m log n), where m is the length of given string that needs to be found.

提交回复
热议问题