Files
XCEngine/docs/api/containers/container-hashmap.md

3.3 KiB
Raw Blame History

HashMap

命名空间: XCEngine::Containers

类型: class (template)

描述: 模板哈希表容器,提供键值对存储和快速查找。

概述

HashMap<Key, Value> 是一个模板哈希表容器,实现了分离链接法的哈希表,支持键值对的插入、查找和删除操作。

公共类型

Pair

成员 类型 描述
first Key
second Value

迭代器

别名 类型 描述
Iterator typename Array<Pair>::Iterator 迭代器类型
ConstIterator typename Array<Pair>::ConstIterator 常量迭代器类型

公共方法

构造/析构

方法 描述
HashMap() 默认构造16 个桶)
explicit HashMap(size_t bucketCount, Memory::IAllocator* allocator = nullptr) 指定桶数量和分配器
~HashMap() 析构函数

拷贝/移动构造

方法 描述
HashMap(const HashMap& other) 拷贝构造
HashMap(HashMap&& other) noexcept 移动构造
HashMap& operator=(const HashMap& other) 拷贝赋值
HashMap& operator=(HashMap&& other) noexcept 移动赋值

元素访问

方法 描述
Value& operator[](const Key& key) 下标访问(不存在时插入)

查找

方法 描述
Value* Find(const Key& key) 查找键对应的值指针
const Value* Find(const Key& key) const 常量查找
bool Contains(const Key& key) const 检查是否包含键

插入/删除

方法 描述
bool Insert(const Key& key, const Value& value) 插入(拷贝值)
bool Insert(const Key& key, Value&& value) 插入(移动值)
bool Insert(Pair&& pair) 插入(移动键值对)
bool Erase(const Key& key) 删除键对应的元素
void Clear() 清空所有元素

容量

方法 描述
size_t Size() const 获取元素数量
bool Empty() const 检查是否为空

迭代器

方法 描述
Iterator begin() 获取开始迭代器
Iterator end() 获取结束迭代器
ConstIterator begin() const 获取常量开始迭代器
ConstIterator end() const 获取常量结束迭代器

内存分配器

方法 描述
void SetAllocator(Memory::IAllocator* allocator) 设置内存分配器

实现细节

常量/成员 类型 描述
DefaultBucketCount static constexpr size_t 默认桶数量16
m_loadFactor float 负载因子阈值0.75

使用示例

#include <XCEngine/Containers/HashMap.h>

// 基本用法
Containers::HashMap<Containers::String, int> map;
map.Insert("one", 1);
map.Insert("two", 2);

// 使用下标访问
map["three"] = 3;

// 查找
int* val = map.Find("one");
if (val) {
    printf("Found: %d\n", *val);
}

// 使用 Contains
if (map.Contains("two")) {
    printf("two exists\n");
}

// 删除
map.Erase("one");

// 迭代
for (auto& pair : map) {
    printf("%s: %d\n", pair.first.CStr(), pair.second);
}

相关文档