【发布时间】:2021-05-17 06:19:38
【问题描述】:
如果我用数组初始化 map STL 中第二个元素的默认值是多少? 例如:
#include <bits/stdc++.h>
using namespace std;
void countFreq(int arr[], int n)
{
unordered_map<int, int> mp;
// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++)
mp[arr[i]]++;
// Traverse through map and print frequencies
for (auto x : mp)
cout << x.first << " " << x.second << endl;
}
int main()
{
int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 };
int n = sizeof(arr) / sizeof(arr[0]);
countFreq(arr, n);
return 0;
}
这个程序如何通过访问map mp的第二个元素返回数组中元素的频率?
【问题讨论】:
-
不在地图中的项目的默认值为0。
-
@drescherjm 假设您使用 operator[]
-
是的,新的映射值为value initialized。对于
int,这意味着zero initialized。 -
当
mp[arr[i]]++执行时,它要么增加一个现有值,要么在必要时创建一个新的键值对并将增量前的值初始化为零。 -
在this documentation 中描述了所发生的事情。如果您是 C++ 文档的新手,可能不清楚,但那里有详细信息。
标签: c++ dictionary data-structures stl