【问题标题】:how an unordered_map is initialized with the values of arrayunordered_map 如何用数组的值初始化
【发布时间】:2019-02-02 14:46:01
【问题描述】:

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

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

【问题讨论】:

    标签: c++ c++11 hashmap


    【解决方案1】:

    在这里,unordered_maphash[arr[i]]++; 以这种方式工作:

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

    2. 1234563因为++ 运算符,它会加一。因此,在操作结束时,值将是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}]
    

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

    【讨论】:

    • @TuhinPanda 这回答了你的问题吗?
    【解决方案2】:

    无序映射的键必须是唯一的,所以所有的 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
    

    【讨论】:

      【解决方案3】:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-19
        • 2016-11-20
        • 2015-09-30
        • 2020-10-20
        • 2021-06-03
        相关资源
        最近更新 更多