为什么在打印unordered_map和map(字典)的键和值时出现异常?

问题描述 投票:0回答:1

这是我的代码,请告诉我为什么它不是从地图开始打印,因为它以正确的方式打印

#include<bits/stdc++.h>
using namespace std;

int main(){
unordered_map<int,int>arr;
for(int i=1;i<=10;i++){
    arr[i]=i*i;
}

for(auto it=arr.begin();it!=arr.end();it++){
    cout<<it->first<<" "<<it->second<<"\n";
}

cout<<"normal map \n";

map<int,int>arry;
for(int i=1;i<=10;i++){
    arry[i]=i*i;
}

for(auto it=arry.begin();it!=arry.end();it++){
    cout<<it->first<<" "<<it->second<<"\n";
}

}

我的输出是

10 100

9 81

8 64

7 49

6 36

5 25

1 1

2 4

3 9

4 16

法线贴图

1 1

2 4

3 9

4 16

5 25

6 36

7 49

8 64

9 81

10 100

为什么un_ordered地图以这种方式打印价值为什么不打印像地图一样

c++ dictionary stl unordered-map
1个回答
1
投票

std::unordered_map不按任何特定顺序订购密钥。这就是它被称为无序的原因。

在内部,元素不按任何特定顺序排序,而是组织成桶。放置元素的哪个存储桶完全取决于其键的哈希值。这允许快速访问单个元素,因为一旦计算了散列,它就是指元素被放入的确切存储桶。

© www.soinside.com 2019 - 2024. All rights reserved.