c++ map是有序还是无序的_C ++:是unordered_map真的无序吗?

I am very confused by the name 'unordered_map'. The name suggests that the keys are not ordered at all. But I always thought they are ordered by their hash value. Or is that wrong (because the name implies that they are not ordered)?

Or to put it different: Is this

typedef map > HashMap;

with

template

struct HashComp {

bool operator

return hash()(v1) < hash()(v2);

}

};

the same as

typedef unordered_map HashMap;

? (Edit: Well, ok not exactly, STL will complain here because there may be keys k1,k2 and neither k1 < k2 nor k2 < k1. You would need to use multimap and overwrite the equal-check.)

Or again differently: When I iterate through them, can I assume that the key-list is ordered by their hash value?

解决方案

In answer to your edited question, no those two snippets are not equivalent at all. std::map stores nodes in a tree structure, unordered_map stores them in a hashtable*.

Keys are not stored in order of their "hash value" because they're not stored in any order at all. They are instead stored in "buckets" where each bucket corresponds to a range of hash values. Basically, the implementation goes like this:

function add_value(object key, object value) {

int hash = key.getHash();

int bucket_index = hash % NUM_BUCKETS;

if (buckets[bucket_index] == null) {

buckets[bucket_index] = new linked_list();

}

buckets[bucket_index].add(new key_value(key, value));

}

function get_value(object key) {

int hash = key.getHash();

int bucket_index = hash % NUM_BUCKETS;

if (buckets[bucket_index] == null) {

return null;

}

foreach(key_value kv in buckets[bucket_index]) {

if (kv.key == key) {

return kv.value;

}

}

}

Obviously that's a serious simplification and real implementation would be much more advanced (for example, supporting resizing the buckets array, maybe using a tree structure instead of linked list for the buckets, and so on), but that should give an idea of how you can't get back the values in any particular order. See wikipedia for more information.

* Technically, the internal implementation of std::map and unordered_map are implemented-defined, but the standard requires certain Big-O complexity for operations that implies those internal implementations

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值