一、hash_map、unordered_map
内部结构:都是采用哈希表实现的。
区别:由于在C标准库中没有定义散列表,标准库的实现提供了一个名为hash_map的非标准散列表。而从C++11开始,哈希表已经添加到C标准库中,决定对类使用备用名称unorder_map。
unordered_map使用
#include <unordered_map>
//取得键和值:
unordered_map<int, int> hash;
unordered_map<Key,T>::iterator it;//迭代器
it->first; // same as (*it).first (the key value)
it->second; // same as (*it).second (the mapped value)
简单例子
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashtable;
for (int i = 0; i < nums.size(); ++i) {
auto it = hashtable.find(target - nums[i]);
if (it != hashtable.end()) {
return {it->second, i};
}
hashtable[nums[i]] = i;
}
return {};
}
};
源码解析
这篇博客介绍了C++标准库中的unordered_map和已弃用的hash_map的区别。unordered_map是C++11引入的哈希表实现,而hash_map是非标准的。通过一个LeetCode第一题的解决方案展示了unordered_map的使用,该问题使用哈希表来查找数组中两个数的索引,使得它们的和等于目标值。

1万+

被折叠的 条评论
为什么被折叠?



