简体   繁体   中英

C++ Unordered Map Constant Time Access?

I am researching the C++ unordered_map container type. I am just verifying something I read from the C++ website on element access with operator[] .

It says that the time complexity is usually constant, but worst case is linear time. Since my application must guarantee constant time access to elements inside of this map, I wanted to verify my understanding of this container.

Whenever my application accesses elements inside of this unordered_map, the object it is looking for is guaranteed to exist, so the container will never try to add in a missing element. Since I am only doing look ups , does that mean that the unordered_map will always give me constant time access ? The linear time case is only for certain cases where an insertion will occur, is that correct?

Edit: The elements inside of the unordered_map are guaranteed to be unique. They hold the addresses of several unique objects existing in memory.

The lookup depends on whether there are hash collisions for any of the existing elements, in which case the elements get put in the same bucket and have to be linearly searched using the equality comparison. The worst case is that everything is in the same bucket.

So you can have a read-only map with linear look-up time complexity, but if you can guarntee no collisions for the existing elements, then you can guarantee O(1) look-up.

Wrong.

Hashmaps have O(1) time for both insert and lookup as long as there are no hash collisions. If there are hash collisions, the complexity is O(m) where m is the number of collisions with the requested hash - up to n if all hashes collide.

It is trivial to construct a case where all hashes collide, it is far from trivial to avoid this case, especially if there is a hostile attacker giving the keys.

If you want guaranteed time bounds, use a treemap, which is O(log n) for lookup and insertion

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM