C++ 哈希集合 、哈希映射的使用 而非 原理 总结

本文深入探讨了哈希集合和哈希映射两种数据结构的使用方法,包括初始化、插入、删除、查找等操作,以及如何使用迭代器访问元素,为理解和应用哈希结构提供了实用指南。

查找某个值是否存在?查询某个值对应的值是什么?下面的数据结构,可以帮助你。

整理来自于力扣:https://leetcode-cn.com/leetbook/detail/hash-table/

有多于的时间,可以去刷一下,只想知道怎么用,看下面的就行。

#include<bits/stdc++.h>     //万能头文件
using namespace std;

int main()
{
    cout<<"-----------------unordered_set----------哈希集合-----------------------";

    //注意:使用这个unordered_set 需要添加 #include <unordered_set>
    //哈希集是集合的实现之一,它是一种存储不重复值的数据结构。

    // 1. 初始化一个hash_set   类型可以根据自己的需求
    unordered_set<int> hashset;

    // 2. 插入新的值
    hashset.insert(3);
    hashset.insert(2);
    hashset.insert(1);

    // 3. 删除值
    hashset.erase(2);

    // 4. 检查一个值是否在hash_set中
    if (hashset.count(2) <= 0) {
        cout << "Key 2 is not in the hash set." << endl;
    }

    // 5. 获得hash_set的大小
    cout << "The size of hash set is: " << hashset.size() << endl;

    // 6. 使用迭代器访问hash_set
    for (auto it = hashset.begin(); it != hashset.end(); ++it) {
        cout << (*it) << " ";
    }
    cout << "are in the hash set." << endl;

    // 7. 清除hash_set的元素
    hashset.clear();

    // 8. 检查hash_set是否为空
    if (hashset.empty()) {
        cout << "hash set is empty now!" << endl;
    }

    cout<<"-------------unordered_map-------------哈希映射--------------------";
    //注意:哈希映射是用于存储 (key, value) 键值对的一种实现        属于一对一的对应关系
    //使用哈希映射的场景是,我们需要更多的信息,而不仅仅是键。然后通过哈希映射建立密钥与信息之间的映射关系。

    // 1. 初始化hash_map 这里的类型可以自己按照需求设计
    unordered_map<int, int> hashmap;

    // 2. 插入一个新的键值对(key, value)
    hashmap.insert(make_pair(0, 0));
    hashmap.insert(make_pair(2, 3));

    // 3. 插入一个键值对或者更新已有的键值对
    hashmap[1] = 1;
    hashmap[1] = 2;

    // 4. 获取指定键的值
    cout << "The value of key 1 is: " << hashmap[1] << endl;

    // 5. 删除一个键值
    hashmap.erase(2);

    // 6. 检查一个键值是否在hash_map中
    if (hashmap.count(2) <= 0) {
        cout << "Key 2 is not in the hash map." << endl;
    }
    // 7. 获取hash_map的大小
    cout << "the size of hash map is: " << hashmap.size() << endl;

    // 8. 使用迭代器访问hash_map
    for (auto it = hashmap.begin(); it != hashmap.end(); ++it) {
        cout << "(" << it->first << "," << it->second << ") ";
    }
    cout << "are in the hash map." << endl;

    // 9. 清楚所有键值
    hashmap.clear();

    // 10. 检查hash_map是否为空
    if (hashmap.empty()) {
        cout << "hash map is empty now!" << endl;
    }

}

以后还有啥,继续添加总结。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值