C++:为什么我的hash_map会给我一个像地图一样有序的结果

C++: Why my hash_map is giving me an ordered result like a map?

本文关键字:地图 一个 一样 结果 map hash C++ 为什么 我的      更新时间:2023-10-16

由于map是使用树和hash_map实现的,我创建了一个代码来测试我的map是否会给我一个有序的结果,hash_map会按照注册的顺序打印我的示例

map<string, int> mymap;
hash_map<string, int> myhashmap;
mymap["lucas"] = 1;
mymap["abel"] = 2;
mymap["jose"] = 1;
myhashmap["lucas"] = 1;
myhashmap["abel"] = 2;
myhashmap["jose"] = 1;
for(map<string, int>::iterator it = mymap.begin(); it != mymap.end(); it++){
    cout << it->first << " " << it->second << endl;
}
cout << endl;
for(hash_map<string, int>::iterator it = myhashmap.begin(); it != myhashmap.end(); it++){
    cout << it->first << " " << it->second << endl;
}

但两个结果都是:

abel 2
jose 1
lucas 1

为什么hashmap给了我一个有序的结果?

hash_map中没有顺序保证,这意味着它可以根据实现情况以任何顺序存储结果。