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(要查找的值),返回值为找到的个数