Files
XCEngine/docs/api/containers/hashmap/operator-subscript.md

38 lines
989 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# HashMap::operator[]
```cpp
Value& operator[](const Key& key);
```
按下标访问键对应的值。如果键不存在,则插入一个默认构造的值并返回引用。
**参数:**
- `key` - 要访问的键
**返回:** 对应值的引用。如果键不存在,则返回一个默认构造的 `Value` 的引用。
**复杂度:** O(1) 平均,最坏 O(n)(发生 rehash 时)
**线程安全:** ❌ 非线程安全
**异常:**
**示例:**
```cpp
XCEngine::Containers::HashMap<int, std::string> map;
map[1] = "one"; // 插入键 1值 "one"
map[2] = "two"; // 插入键 2值 "two"
std::string& value = map[1]; // 获取键 1 对应的值,结果为 "one"
map[3]; // 插入键 3值为 std::string 的默认构造值
```
## 相关文档
- [HashMap 总览](hashmap.md) - 返回类总览
- [Find](find.md) - 查找键对应的值(不插入)
- [Insert](insert.md) - 插入键值对(不覆盖已存在的键)