C++环境下如何使用STL中的unordered_map和unordered_set容器实现哈希查找

一、unordered_map是一种容器,它存储的元素是键值对,并且基于哈希表实现。这意味着可以通过键快速查找对应的值,查找操作的平均时间复杂度为 O(1)。例如下面这个代码的键是string类型的,值是int 类型的。

二、代码

#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;

int main() 
{
    // 创建一个 unordered_map 容器,键为 string 类型,值为 int 类型
    unordered_map<string, int> studentscores;

    // 插入一些键值对
    studentscores["Alice"] = 85;
    studentscores["Bob"] = 92;
    studentscores["Charlie"] = 78;

    // 查找特定键的值
    string name = "Bob";
    auto it = studentscores.find(name);
    if (it != studentscores.end()) 
    {
        cout << name << " 的分数是: " << it->second << endl;
    } 
    else 
    {
        cout << "未找到 " << name << " 的分数。" << endl;
    }

    return 0;
}

三、unordered_map跟vector一样都是容器。然后下面这条语句中的auto是C++11引入的一个关键字,用于自动推导变量的类型。在这个语句中,编译器会根据 studentScores.find(name) 的返回值类型来自动确定 it 的类型。这行代码的作用是在 studentscores 这个 unordered_map 容器中查找键为 name 的元素,并将指向该元素(如果找到)或指向 unordered_map 末尾(如果未找到)的迭代器赋值给变量 it。后续可以通过检查 it 是否等于 studentscores.end() 来判断是否找到了指定键的元素。

auto it = studentscores.find(name);

四、it -> second 表示的是:it是一个迭代器 (可以理解为指针),first表示键,second表示值,it -> second 就是访问对应的值部分。

五、unordered_set也是基于哈希表实现的容器,查找操作的平均时间复杂度同样是 O(1)。此代码创建了一个unordered_set来存储整数,然后使用find方法检查特定元素是否存在于集合里,并输出相应的结果。

六、代码 

#include <iostream>
#include <unordered_set>
using namespace std;

int main() 
{
    // 创建一个 unordered_set 容器,存储 int 类型的元素
    unordered_set<int> numbers = {1, 2, 3, 4, 5};

    // 查找特定元素是否存在
    int target = 3;
    if (numbers.find(target) != numbers.end()) 
    {
        cout << target << " 存在于集合中。" << endl;
    } 
    else 
    {
        cout << target << " 不存在于集合中。" << endl;
    }

    return 0;
}

七、上面第一个程序unordered_map的时间复杂度分析:插入一些键值对对应的插入操作的时间复杂度是O(1);然后是find()函数的查找操作,因为它是基于哈希查找算法实现的,所以对应的时间复杂度是O(1);所以,整个程序的时间复杂度为O(1)。 

八、上面的第二个程序unordered_set的时间复杂度分析:find()函数的查找操作也是基于哈希查找算法实现的,所以对应的时间复杂度也是O(1)。整个程序的时间复杂度为O(1)。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值