哈希映射 unordered_map

哈希映射 - 用法

哈希映射是用于存储 (key, value) 键值对的一种实现。

我们提供了一个在 Java、C++ 和 Python 中使用哈希映射的示例。如果您还不熟悉哈希映射的用法,那么浏览一下这个示例将很有帮助。

#include<unordered_map>
using namespace std;

int main()
{
    unordered_map<int,int>hashmap;
    //insert a new(key,value)pair
    hashmap.insert(make_pair(0.0));
    //another way to insert a (key,value);
    hashmap.insert(unordered_map<int,int>::value_type(1,2));
    //insert a new (key,value)pair or update the value of the existed (key value)
    hashmap[0]=1;
    hashmap[1]=3;
    //get thr value of the specific key
    cout<<"the value of the key 1 is"<<hashmap[1]<<endl;
    //delete a key
    hashmap.erase(1);
    //check if a key is in the hash map
    if(hashmap.count(2))
        cout<<"key is not in the hash map"<<endl;
    //get the size of the hash map;
    cout<<"the size of the hashmap is "<<hashmap.size()<<endl;
    //iterate the hash map
    for(auto it=hashmap.begin();it!=hashmap.end();it++)
    {
        cout<<"("<<it.first()<<","<<it.second()<<")"
    }
    //clear the map
    hashmap.clear();
    //check if the map is empty
    if(hashmap.empty())
        cout<<"hashmap is empty now"<<endl;

}
 场景 I - 提供更多信息

使用哈希映射的第一个场景是,我们需要更多的信息,而不仅仅是键。然后通过哈希映射建立密钥与信息之间的映射关系

示例


让我们来看一个例子:

 

给定一个整数数组,返回两个数字的索引,使它们相加得到特定目标。

在这个例子中,如果我们只想在有解决方案时返回 true,我们可以使用哈希集合来存储迭代数组时的所有值,并检查 target - current_value 是否在哈希集合中。

但是,我们被要求返回更多信息,这意味着我们不仅关心值,还关心索引。我们不仅需要存储数字作为键,还需要存储索引作为值。因此,我们应该使用哈希映射而不是哈希集合。

 

更重要的是


在某些情况下,我们需要更多信息,不仅要返回更多信息,还要帮助我们做出决策

 

在前面的示例中,当我们遇到重复的键时,我们将立即返回相应的信息。但有时,我们可能想先检查键的值是否可以接受。

 * Template for using hash map to find duplicates.
 * Replace ReturnType with the actual type of your return value.
 */
ReturnType aggregateByKey_hashmap(vector<Type>& keys) {
    // Replace Type and InfoType with actual type of your key and value
    unordered_map<Type, InfoType> hashtable;
    for (Type key : keys) {
        if (hashmap.count(key) > 0) {
            if (hashmap[key] satisfies the requirement) {
                return needed_information;
            }
        }
        // Value can be any information you needed (e.g. index)
        hashmap[key] = value;
    }
    return needed_information;
}

 

posted @ 2019-11-27 22:55  任仁人  阅读(28)  评论(0编辑  收藏  举报