What is the fastest way to figure out if an unordered_map
container has an item with a specified key?
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.