简体   繁体   中英

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

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, or does it use a hash function or what?

Log(n) It is based on a red black tree.

Edit: n is of course the number of members in the map.

std::map and std::set are implemented by compiler vendors using highly balanced binary search trees (eg 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.

It does not iterate all elements, it does a binary search (which is O(log(n))). It use operator< or a comparator to do the search.

If you want a hash map, you can use a std::unordered_map (added on C++-0x), which use a hash function and on average (depending on the hash function and data you provide) find() will be O(1).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM