简体   繁体   English

C ++无序映射常量时间访问?

[英]C++ Unordered Map Constant Time Access?

I am researching the C++ unordered_map container type. 我正在研究C ++ unordered_map容器类型。 I am just verifying something I read from the C++ website on element access with operator[] . 我只是验证我从C ++网站上读取的有关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. 每当我的应用程序访问此unordered_map中的元素时,它所寻找的对象都保证存在,因此容器将永远不会尝试添加缺少的元素。 Since I am only doing look ups , does that mean that the unordered_map will always give me constant time access ? 由于我只是在查看 ,这是否意味着unordered_map总是会给我一些时间访问 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. 编辑:unordered_map内的元素保证是唯一的。 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. 因此,您可以拥有具有线性查找时间复杂度的只读映射,但如果您可以保证现有元素不会发生冲突,则可以保证O(1)查找。

Wrong. 错误。

Hashmaps have O(1) time for both insert and lookup as long as there are no hash collisions. 只要没有哈希冲突,哈希映射就会有插入和查找的O(1)时间。 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. 如果存在哈希冲突,则复杂度为O(m) ,其中m是与请求的哈希冲突的数量 - 如果所有哈希冲突,则最多为n。

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 如果需要保证时间范围,请使用树形图,即O(log n)进行查找和插入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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