我遇到一个让我感到困惑的代码,unordered_map的初始化如下所示
std::unordered_map<std::string, int> wordMap;
// Inserting elements through an initializer_list
wordMap.insert({ {"First", 1}, {"Second", 2}, {"Third", 3} } );
但是让我惊讶的是下面的代码
int arr[] = { 1, 5, 2, 1, 3, 2, 1 };
unordered_map<int, int> hash;
for (int i = 0; i < n; i++)
hash[arr[i]]++;
这里我不知道如何在地图中插入键和值
答案 0 :(得分:1)
这里,在unordered_map
中,hash[arr[i]]++;
的工作方式如下:
它搜索一个键(arr [i])。如果找到,则将相应的值增加1
。
如果未找到,将使用键arr[i]
创建一个新元素,并且由于值的类型为int
,因此将为其存储默认值0
。由于使用++
运算符,它将被加1。因此,在操作结束时,该值为1
。
为使您的示例非常明确,它的工作方式如下:
i = 0 => arr[i] = 1 => Not present in map => New pair added => hash: [{1, 1}]
i = 1 => arr[i] = 5 => Not present in map => New pair added => hash: [{1, 1}, {5, 1}]
i = 2 => arr[i] = 2 => Not present in map => New pair added => hash: [{1, 1}, {5, 1}, {2, 1}]
i = 3 => arr[i] = 1 => Present in map => Existing pair updated => hash: [{1, 2}, {5, 1}, {2, 1}]
i = 4 => arr[i] = 3 => Not present in map => New pair added => hash: [{1, 2}, {5, 1}, {2, 1}, {3, 1}]
i = 5 => arr[i] = 2 => Present in map => Existing pair updated => hash: [{1, 2}, {5, 1}, {2, 2}, {3, 1}]
i = 6 => arr[i] = 1 => Present in map => Existing pair updated => hash: [{1, 3}, {5, 1}, {2, 2}, {3, 1}]
此处提到的顺序可能与实际顺序不同。上面的解释只是为了解释事情。
答案 1 :(得分:0)
operator []检查元素是否存在。如果没有,它将使用默认构造函数创建一个并返回引用(或对其的const引用)。即:
hash[arr[0]]++
it creates hash[1]first
是
hash[1]++ => hash[1]=hash[1]+1 which is 0+1 ( since hash[1] at the begining was 0 by default.. )
when it get to the second 1 it become hash[1]=hash[1]+1 = 2 ...
..ect same for other values
基本上是在创建并计算数组中重复项的数量
最后它会给你
hash[1]=3
hash[2]=2
hash[3]=1
hash[5]=1
答案 2 :(得分:0)
无序映射的键必须唯一,因此所有1:s都将组合在一起。但是当它们合并时,循环将在值侧加1:
hash [arr [i]] ++将等于以下示例:hash [1] + = 1;
由于存在三个1值,因此hash [1]的值将为3。您将找到两个值2的记录,这将使hash [2] = 2。
#include <iostream>
#include <unordered_map>
int main()
{
int arr[] = { 1, 5, 2, 1, 3, 2, 1 };
std::unordered_map<int, int> hash;
for (int i = 0; i < 7; i++) {
hash[arr[i]] += 1;
}
for (auto i : hash) {
printf("%i:%i\n", i.first, i.second);
}
}
# Output:
# 3:1
# 2:2
# 5:1
# 1:3