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

前端 未结 2 904
灰色年华
灰色年华 2021-02-02 08:34

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

相关标签:
2条回答
  • 2021-02-02 09:23

    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());

    0 讨论(0)
  • 2021-02-02 09:34

    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.

    0 讨论(0)
提交回复
热议问题