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?
Time Complexity for Searching element : The time complexity for searching elements in std::map is O(log n).
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.
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.
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.
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 (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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With