unordered_map: which one is faster find() or count()?

眉间皱痕 提交于 2019-12-03 08:29:50

问题


What is the fastest way to figure out if an unordered_map container has an item with a specified key?


回答1:


They will have about equal performance. You should use the algorithm that best expresses what you are trying to do.

To elaborate on that, generally count() will be implemented using find(). For example, in libcxx, count() is implemented as return (find(__k) != end());




回答2:


find() and count() are applicable to many containers in C++.

For maps, sets etc. find will always have constant execution time, since it just calculate the hash, and returns an iterator to the first element found (end() if not found).

count() on the other hand, has a constant execution time O(e), where e is the number of times the provided key is found. The worst case is a collection where all members are the same, so count could have a complexity O(n)

map or unordered_map do not allow for duplicates, therefore their asymptotic run time would be the same.

The choice depends on the semantics in your code. If you want just to check if a key exist, you could just use count. If you would like to check if a key exists, and use its value, then go for find since you will already have an iterator pointing to that element.



来源:https://stackoverflow.com/questions/14159682/unordered-map-which-one-is-faster-find-or-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!