关于 map 和 unordered_map 疑问
  • 板块学术版
  • 楼主Galexccddne
  • 当前回复3
  • 已保存回复3
  • 发布时间2023/8/1 12:42
  • 上次更新2023/11/3 06:35:21
查看原帖
关于 map 和 unordered_map 疑问
483037
Galexccddne楼主2023/8/1 12:42

rt,对于如下代码:

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

int read() {
	int s = 0, f = 1;
	char ch = getchar();
	while (ch < '0' || ch > '9')
		f = (ch == '-' ? -1 : 1), ch = getchar();
	while (ch >= '0' && ch <= '9')
		s = (s << 1) + (s << 3) + (ch ^ 48), ch = getchar();
	return s * f;
}

int a[20] = {25, 92, 98, 26, 73, 52, 59, 79, 67, 78, 87, 45, 60, 11, 86, 58, 76, 96, 30, 18};
int b[20] = {5, 1058, 28, 676, 5329, 338, 3481, 6241, 4489, 6084, 7569, 75, 450, 121, 7396, 3364, 722, 18, 900, 12};
map<int, int> tmp, rep;

signed main() {
	for (int i = 0; i < 20; i++)
		tmp[a[i]]++, rep[a[i]] = b[i];
	int ans = 0;
	for (auto x : tmp) {
		cout << x.first << ' ' << x.second << endl;
		if (!tmp[rep[x.first]])
			ans += x.second;
		else if (x.first < rep[x.first])
			ans += max(x.second, tmp[rep[x.first]]);
	}
	return 0;
}

运行后得到的输出是

11 1
18 1
25 1
26 1
30 1
45 1
52 1
58 1
59 1
60 1
67 1
73 1
75 0
76 1
78 1
79 1
86 1
87 1
92 1
96 1
98 1
121 0
338 0
450 0
676 0
722 0
900 0
1058 0
3364 0
3481 0
4489 0
5329 0
6084 0
6241 0
7396 0
7569 0

然而,将代码中的 map 改为 unordered_map 后,输出变为:

30 1
76 1
58 1
76 1
30 1

第二份代码的输出显然是不正确的。但是是什么导致 unordered_map 出现这种问题呢?

求解答。

2023/8/1 12:42
加载中...