gpt4 book ai didi

c++ - 如何使用数组的值初始化 unordered_map

转载 作者:行者123 更新时间:2023-11-30 04:52:18 28 4
gpt4 key购买 nike

我遇到了一段让我感到困惑的代码,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]]++;

这里我不知道如何在 map 中插入键和值

最佳答案

这里,在unordered_map中,hash[arr[i]]++;是这样工作的:

  1. 它搜索一个键 (arr[i])。如果找到,则相应的值增加1

  2. 如果没有找到,将创建一个新元素,键为 arr[i],因为值是 int 类型,默认值为 0 是为它存储的。因为 ++ 运算符,它会加一。因此,在操作结束时,该值将为 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}]

这里所说的顺序可能与实际顺序不同。以上解释只是为了说明事情。

关于c++ - 如何使用数组的值初始化 unordered_map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54494115/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com