C++的三大容器之无序容器

文章介绍了C++中的无序容器,如unordered_map,强调了在使用自定义类作为键时需重载相等比较和提供hash函数。示例代码展示了如何为Point结构体定义这些操作,并插入数据到unordered_map中。
摘要由CSDN通过智能技术生成

无序容器的类型就是在有序容器基础上加个unordered前缀,分别是:unordered_set/unordered_multiset、unordered_map/unordered_multimap,
无序容器的用法也和有序容器一样,不同点在于无序容器的内部数据结构是散列表。

因为用法基本和有序容器一致,所以我这边直接跳过,有兴趣的小伙伴可以去看我的另外一篇文章《C++的三大容器之有序容器》,我们这边只聊聊对于自定义类需要注意哪些:

#include <iostream>
#include <unordered_map>
#include <algorithm>

struct Point
{
    Point(int x, int y) : m_x(x), m_y(y)
    {}
    int m_x, m_y;
    bool operator==(const Point& other) const
    {
        return m_x == other.m_x;   // 自定义相等比较运算
    }

};

int main()
{
    auto hasher = [](const Point& p)    // 定义一个lambda表达式,用来计算 hash 值
    {
        return std::hash<int>()(p.m_x);  // 调用标准hash函数对象计算
    };

    std::unordered_map<Point, int, decltype(hasher)> dict(10, hasher);

    dict[Point(2, 3)] = 2;
    dict.emplace(Point(1, 2), 3);
    dict.insert({Point(6, 7), 5});

    for (auto i : dict)
    {
        std::cout << i.first.m_x << " " << i.first.m_y << " " << i.second << std::endl;
    }

    return 0;
}

运行结果如下:
在这里插入图片描述
平时项目中,不知道大家碰到调用无序容器的概率是多少?我印象中,好像很难碰到这种场景。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值