Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 795
Publius Avatar asked Apr 01 '12 03:04

Publius


People also ask

What is the time complexity of find in map?

Time Complexity for Searching element : The time complexity for searching elements in std::map is O(log n).

What is the time complexity of Find function in C++?

find(): Searches for a particular element and returns the iterator pointing to the element if the element is found otherwise it will return the iterator returned by end(). Its time complexity is O(logN) where N is the size of the set.

What does map return if key not found C++?

end() if the key is not found. Show activity on this post. std::map operator[] inserts the default constructed value type in to the map if the key provided for the lookup doesn't exist. So you will get an empty string as the result of the lookup.

How do you search on a map?

Search for a place on Google MapsAt the top, tap the search box and enter an address, name of a place, or choose a category, like gas stations or groceries. Tip: After you find a place on the map, you can check directions to the place in a list, details about a place, or get directions with voice-guided navigation.


2 Answers

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

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

like image 193
David D Avatar answered Sep 18 '22 09:09

David D


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.

like image 28
Arif Ali Saiyed Avatar answered Sep 19 '22 09:09

Arif Ali Saiyed