C++ unordered_map的用法


一、簡介

unordered_map是C++新標准加入的對hash_map的官方實現。

unordered_map是一個將key與value關聯起來的容器,根據key值來查找value,其底層實現原理為哈希表。

unordered_map存儲是沒有順序的,只是根據key值將value存在指定的位置,所以我們可以在O(1)時間內查找value的值。

unordered_map可以使用[]操作符來訪問key值對應的value值。

二、一個使用到了unordered_map的例子

題目來源:LeetCode 347  Top K Frequent Elements

給你一個整數數組 nums 和一個整數 k ,請你返回其中出現頻率前 k 高的元素。你可以按 任意順序 返回答案。

示例 1:

輸入: nums = [1,1,1,2,2,3], k = 2
輸出: [1,2]
示例 2:

輸入: nums = [1], k = 1
輸出: [1]

代碼實現:

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int> counts;
        for(const int& num:nums){
            counts[num]++;
        }
        vector<pair<int,int>> bin;
        for(const pair<int,int>& p:counts){
            bin.push_back(p);
        }
        sort(bin.begin(),bin.end(),[](pair<int,int> p1,pair<int,int> p2){
            return p1.second>p2.second;
        });
        vector<int> ans;
        for(int i=0;i<k;i++){
            ans.push_back(bin[i].first);
        }
        return ans;
    }
};

在這道題中,我們使用到了unordered_map來記錄nums中每個元素出現的次數——將nums中的元素來作為key,其frequency作為value。

然后,由於題目要求我們找到出現頻率前k高的例子,我們需要對unordered_map中的元素根據value進行排序。所以這里介紹一下對unordered_map中根據value

進行排序的方法:

   1、構建新的類型:typedef pair<int, int> PAIR;
   2、對於step1構造的類型,新建一個vector:vector<PAIR> vec;  // 重新定義類型
   3、將unordered_map 中的值重新裝入新定義的vector中:unordered_map<int,int> ans;
        for(auto it=ans.begin();it!=ans.end();it++)
            vec.push_back(make_pair(it->first, it->second));
   4、重載排序規則:
        int cmp(const PAIR& x, const PAIR& y)  
        {  
            return x.second > y.second;   // 按照次數升序排序   
        }
   5、進行排序:
        sort(vec.begin(), vec.end(), cmp);  // vector根據cmp的規則進行排序
   6、完成,此時的vector就是一個unordered_map安裝value排序的

常用功能函數:

find函數:函數形式——哈希表變量名.find(要查找的值),返回值為迭代器在該數據結構所在位置

count函數
如下程序所示,函數形式 哈希表變量名.count(要查找的值),返回值為找到的個數


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM