无序容器的类型就是在有序容器基础上加个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;
}
运行结果如下:
平时项目中,不知道大家碰到调用无序容器的概率是多少?我印象中,好像很难碰到这种场景。